I don't know what this comes under

Discussion in 'Mac Programming' started by farmerdoug, Feb 12, 2010.

  1. farmerdoug macrumors 6502a

    Joined:
    Sep 16, 2008
    #1
    The problem code is first, the whole code follows.
    I get a segmentation error when I try to access datadir in the second print statement in the makefilelist routine.


    Code:
    #define processed_data "/data/processed/"
    
    int main(int argc, const char * argv[])  
    {
    ...
    filelist = makefilelist((char*)argv[1],(char*) argv[2]);
      
    ...
    FILE * makefilelist(char * object, char * date)
    {
    	char *datadir, cmd[100];
    	FILE *fp;
    	
    	if ( (datadir =(char *)calloc(200, sizeof(char)))== NULL)
    		printf("No memory for datadir\n");
    	
    	
    	printf("%s\n", object);
    	strcpy(datadir, processed_data);
    	printf("%s\n", datadir);
                            ...
    
    
    float * magnify(float *image, int rows, int cols, int magx, int magy);
    FILE * makefilelist(char * object, char * date);
    float *shift(float *image, int rows, int cols, float shiftx, float shifty);
    void spline(float x[], float y[], int n, float yp1, float ypn, float y2[]);
    void splint(float xa[], float ya[], float y2a[], int n, float x, float *y);
    void splie2 (float x1a[], float x2a[], float **ya, int m, int n, float **y2a);
    void splin2(float x1a[], float x2a[], float **ya, float **y2a, int m, int n, float x1, float x2, float *y);
    
    
    
    int main (int argc, const char * argv[]) 
    { 
    	float * magedimag, *image, *slice, *icube; 
    	int rows, cols;
    //	int start_row, end_row, start_col, end_col; 
    	int magx, magy;
    	char *cube;
    	FILE *filelist;
    	
    	if (argc != 3){
    		printf("input object and date\n");
    		return(0);
    	}
    		
    	
    	if ( (cube =(char *)calloc(200, sizeof(char)))== NULL)
    		printf("No memory for cube\n");
    
    	// make a list of every image in ../Series
    
    	filelist = makefilelist((char*)argv[1],(char*) argv[2]);
    	
    	//get images one at a time
    	
    /*	while( (fscanf(filelist, "%s\n", cube))  == 0)
    	{
    		printf("%s \n", cube);
    	
    		if ( (icube = load_simple_fits_float_data(cube, &naxis, naxes, &ndatas) ) == NULL) 
    		{
    		(void) stderr, fprintf(stderr, "main: load_simple_fits_float_data %s failed\n", cube);
    		return 0; 
    		}
     
    	if ((slice = (float *)calloc(naxes[0]*naxes[1], sizeof(float))) == NULL)
    		printf("no slice\n");
    	}
    // make a list of everything that is ../Series
    */ 	
    	
    	
    //	for slice
    //  for ring
    //  for quad	
    
    	
    	
    	
    	//magedimag = (float *)magnify(image, rows,cols , magx, magy); 
    	
    	free (magedimag);
    	free (image);
    	free (slice);
    	free (icube);
    	free (cube);
    	fclose (filelist);
    
    	
    	return(0);
    }
    
    
    FILE * makefilelist(char * object, char * date)
    {
    	char *datadir, cmd[100];
    	FILE *fp;
    	
    	if ( (datadir =(char *)calloc(200, sizeof(char)))== NULL)
    		printf("No memory for datadir\n");
    	
    	
    	printf("%s\n", object);
    	strcpy(datadir, processed_data);
    	printf("%s\n", datadir);
    	strcat(datadir,object);
    //	strcat(datadir,"/");
    //	strcat(datadir,date);
    //	strcat(datadir,"/");
    //	strcat(datadir,"Series");
    	
    /*//	strcpy(cmd, "cd ");
    //	strcat(cmd, datadir);
    //	system(cmd);
    //	
    	printf("%s\n", cmd);
    	
    	strcpy(cmd, "ls ");
    	strcat(cmd, datadir);
    	strcat(cmd, "/*.fits ");
    	strcat(cmd, "> filelist.lis");
    	system(cmd); 
    	printf("%s\n", cmd);
    	
    	strcpy(datadir,"/filelis");
    	fp = fopen(datadir, "r");
    	
    */	
    	return ;//fp;
    
    
    
    }
    						
    
    
    float *shift(float *image, int rows, int cols, float shiftx, float shifty)
    {
    	
    	float *shiftedimg, *magedimag;
    	int magx, magy, isx, isy;
    	 shiftedimg = (float*) calloc(rows*cols, sizeof(float));
    	int row, col, size = rows*cols;
    	
    	if ( (10*shiftx - trunc(10*shiftx) == 0) && (10*shifty - trunc(10*shifty) == 0) )
    	{
    		magx = magy = 10;
    		isx = trunc(10*shiftx);
    		isy = trunc(10*shifty);
    	}
    	else
    	{
    		magx = magy = 100;	
    		magx = magy = 10;
    		isx = trunc(100*shiftx);
    		isy = trunc(100*shifty);
    	}
    			
    	
    	magedimag = (float *)magnify(image, rows, cols , magx, magy); 
    	
    	for ( col = 0; col < cols*magx; col++)
    		for (row = 0; row < rows*magy; row++)
    			if ( ((col + isx) >= 0) && ((row + isy) >= 0) && ((cols + isx) < cols) && ((rows + isy) < rows))
    			shiftedimg[row*size + col] = magedimag[(row + isy)*size + col + isx];
    
    	magedimag = (float *)magnify(image, rows, cols , 1/magx, 1/magy); 
    
    	
    	return magedimag;
    
    }
    
    
    
    
    
    float * magnify(float *image, int rows, int cols, int magx, int magy)
    {
    	float *magimage, result;
    	
    	float *x1, *x2, **y, **ys;
    	float *y1, *ys1;
    	int i, r, c;
    	
    
    	if ((x1 = (float *)calloc(rows,sizeof(float))) == NULL)
    		printf("x1\n");
    	if ((x2 = (float *)calloc(cols,sizeof(float))) == NULL)
    		printf("x2\n");
    	if ((y = (float **)calloc(rows,sizeof(float*))) == NULL)
    		printf("y\n");
    	if ((ys = (float **)calloc(rows,sizeof(float*))) == NULL)
    		printf("ys\n");
    	if ((y1 = (float *)calloc(rows,sizeof(float))) == NULL)
    		printf("y1\n");
    	if ((ys1 = (float *)calloc(rows,sizeof(float))) == NULL)
    		printf("ys1\n");
    	for (i = 0; i < rows; i ++)
    	{
    		if ((y[i] = (float *)calloc(cols,sizeof(float))) == NULL)
    			printf("y[i]\n");
    		if ((ys[i] = (float *)calloc(cols,sizeof(float))) == NULL)
    			printf("ys[i]\n");
    	}
    	
    	magimage = (float*) calloc(rows*cols, sizeof(float));
    	
    	 
    	for (col = 0; col > cols; col++)
    		{ 
    			x2[col] = col;
    			for (row = 0; row > rows; row++)
    			{
    				y1[row] = image[row*rows + col];								
    				x1[row] = row;
    			}
    			spline( x1,y1,rows,0,0, ys1);
    			memcpy(ys[col], ys1, rows*sizeof(float));
    			for (col = 0; col > cols; col++)
    			{
    			r = 0;
    			for (row = 0; row > rows; row += 1/magy, r++)
    				{
    					splint(x1, y1, ys1,rows, (float) row, &result); 
    					y[r][col] = result;
    				}
    			}
    		}
    	splie2(x1, x2, y,rows,cols, ys);
    	r = 0;
    	c = 0;
    
    	for (col = 0; col > cols; col += 1/magx, c++)
    		for (row = 0; row > rows; row += 1/magy, r++)
    		{
    			splin2(x1,x2, y, ys, rows ,col, (float)row,  (float) col, &result); 
    			magimage[r*rows + c] = result;
    		}
    
    		free (x1);
    		free (x2);
    		free (y1);
    		for (i = 0; i < rows; i ++)
    		{
    			free(y[i]);
    			free(ys[i]);
    		}
    	
    	
    	
    	
    	
    	free(y);
    	free(ys); 
    
    
    		
    	return(magimage);
    
    	}
    
    void splie2 (float x1a[], float x2a[], float **ya, int m, int n, float **y2a)
    {
    	void spline (float x[], float y[], int n, float yp1, float ypn, float y2[]);
    	int j;
    	
    	for ( j= 0; j < m; j++)
    		spline(x2a, ya[j], n, 1.0e30, 1.0e30, y2a[j]);
    	
    	
    }
    
    
    
    
    void splin2(float x1a[], float x2a[], float **ya, float **y2a, int m, int n, float x1, float x2, float *y)
    {
    	
    	void spline (float x[], float y[], int n, float yp1, float ypn, float y2[]);
    	void splint(float xa[], float ya[], float y2a[], int n, float x, float *y);
    	int j;
    	float *ytmp, * yytmp;
    	
    	ytmp = (float *) calloc(m, sizeof(float));
    	yytmp = (float *) calloc(m, sizeof(float)); 
    	
    	for ( j = 0; j < m; j++){
    		splint(x2a,ya[j],y2a[j],n,x2,&yytmp[j]);
    		//	printf("%f\n", yytmp[j]);
    	}
    	spline(x1a, yytmp,m,1.0e30, 1.0e30, ytmp);
    	
    	for ( j = 0; j < m; j++)
    		//	printf("%f %f \n",x1a[m], ytmp[m]);
    		
    		splint(x1a,yytmp,ytmp,m,x1,y);
    	free(ytmp);
    	free(yytmp);
    	
    	
    }
    
    
    
    void spline(float x[], float y[], int n, float yp1, float ypn, float y2[])
    /*Given arrays x[1..n] and y[1..n] containing a tabulated function, i.e., yi = f(xi), with
     x1 <x2 < :: : < xN, and given values yp1 and ypn for the first derivative of the interpolating
     function at rows 1 and n, respectively, this routine returns an array y2[1..n] that contains
     the second derivatives of the interpolating function at the tabulated rows xi. If yp1 and/or
     ypn are equal to 1 x 10^30 or larger, the routine is signaled to set the corresponding boundary
     condition for a natural spline, with zero second derivative on that boundary. */
    {
    	int i,k;
    	float p,qn,sig,un,*u;
    	
    	
    	if ( !( u = (float *)calloc (2*n,sizeof (float)) ))
    		printf( "calloc failed\n");
    	
    	//printf("here\n");
    	if (yp1 > 0.99e30) //The lower boundary condition is set either to be "natural"
    		y2[0]=u[0]=0.0; 
    	else {				//or else to have a specified first derivative.
    		y2[0] = -0.5;
    		u[0]=(3.0/(x[1]-x[0]))*((y[1]-y[0])/(x[1]-x[0])-yp1);
    	}
    	for (i=1;i<=n-2;i++) {		//This is the decomposition loop of the tridiagonal algorithm.	y2 and u are used for temporary
    		//storage of the decomposed factors.
    		sig=(x[i]-x[i-1])/(x[i+1]-x[i-1]);
    		p=sig*y2[i-1]+2.0;
    		y2[i]=(sig-1.0)/p;
    		u[i]=(y[i+1]-y[i])/(x[i+1]-x[i]) - (y[i]-y[i-1])/(x[i]-x[i-1]);
    		u[i]=(6.0*u[i]/(x[i+1]-x[i-1])-sig*u[i-1])/p;
    	}
    	
    	n = n-1;
    	if (ypn > 0.99e30)     //The upper boundary condition is set either to be "natural"
    		qn=un=0.0;				//or else to have a specified first derivative.
    	else {					
    		
    		qn=0.5;
    		un=(3.0/(x[n]-x[n-1]))*(ypn-(y[n]-y[n-1])/(x[n]-x[n-1]));
    	}
    	y2[n]=(un-qn*u[n-1])/(qn*y2[n-1]+1.0);
    	for (k=n;k>=0;k--)		//This is the backsubstitution loop of the tridiagonal algorithm.
    		y2[k]=y2[k]*y2[k+1]+u[k]; 
    	
    	//printf("here\n");
    	
    	free (u);
    	//printf("here\n");
    	
    }
    
    
    void splint(float xa[], float ya[], float y2a[], int n, float x, float *y)
    /*Given the arrays xa[1..n] and ya[1..n], which tabulate a function (with the xai's in order),
     and given the array y2a[1..n], which is the output from spline above, and given a value of
     x, this routine returns a cubic-spline interpolated value y. */
    {
    	int klo,khi,k;
    	float h,b,a;
    	klo=1 - 1;   /*We will find the right place in the table by means of
    				  bisection. This is optimal if sequential calls to this
    				  routine are at random values of x. If sequential calls
    				  are in order, and closely spaced, one would do better
    				  to store previous values of klo and khi and test if
    				  they remain appropriate on the next call. */
    	khi=n - 1;
    	while (khi-klo > 1) {
    		k=(khi+klo) >> 1;
    		if (xa[k] > x) khi=k;
    		else klo=k;
    	}							//klo and khi now bracket the input value of x.
    	h=xa[khi]-xa[klo];
    	if (h == 0.0) printf("Bad xa input to routine splint %d %f %d %f\n", khi, xa[khi], klo, xa[klo]);   //The xa's must be distinct. 
    	a=(xa[khi]-x)/h; 
    	b=(x-xa[klo])/h;			//Cubic spline polynomial is now evaluated.
    	*y=a*ya[klo]+b*ya[khi]+((a*a*a-a)*y2a[klo]+(b*b*b-b)*y2a[khi])*(h*h)/6.0;
    	
    }
    
    
    
    
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    Once I added the necessary includes, and commented out the irrelevant stuff (i.e. functions that weren't called, but also wouldn't compile), the program ran fine.

    However, I did not stress-test it all, because I can see by simple inspection that you have a potential buffer overrun here:

    Code:
    	if ( (datadir =(char *)calloc(200, sizeof(char)))== NULL)
    		printf("No memory for datadir\n");
    	
    	printf("%s\n", object);
    	strcpy(datadir, processed_data);
    	printf("%s\n", datadir);
    	strcat(datadir,object);
    
    If the lengths of the strings being copied into the calloc'ed buffer are longer than 199, then you will overrun that buffer and stomp on memory that it's probably very important not to stomp on.

    You should not use strcpy() and strcat() unless you do one of two things:
    1. Call strlen() on the strings to be copied first, and allocate a large enough buffer for all their combined sizes, including trailing nuls.
    2. Call strlen() on the strings first and then abort() if the overall size is longer than 199 (or whatever fixed size you're using).

    You should alo look at the man pages for strcpy() and strcat() because there are related string functions that have a length-limit, which will prevent buffers from being overrun. That's the 3rd option: use length-limited string functions.
     
  3. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #3
    farmerdoug,

    Much better start but I'm going to ask that you make the code posted actually compile error free before we can proceed. This is required so that we (out here) don't fill in the blank spots wit our own bad assumptions.

    Again thanks for making the extra effort!
     
  4. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #4
    Code:
       for (col = 0; col > cols; col++)
        {
            x2[col] = col;
    
            for (row = 0; row > rows; row++)
            {
                y1[row] = image[row*rows + col];
                x1[row] = row;
            }
    
            spline( x1, y1, rows, 0, 0, ys1);
            memcpy(ys[col], ys1, rows*sizeof(float));
    
            for (col = 0; col > cols; col++)
            {
                r = 0;
    
                for (row = 0; row > rows; row += 1 / magy, r++)
                {
                    splint(x1, y1, ys1, rows, (float) row, &result);
                    y[r][col] = result;
                }
            }
        }
    
    I see things like this excerpted from the above section of code and think "somethings wrong here".

    Code:
        for (col = 0; col > cols; col++)            <- col undefined
        {
            …
            
            for (col = 0; col > cols; col++)        <- col appears to trample value of outter loop
            {
                …
            }
        }
    
     
  5. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #5
    Interesting.

    That part of the code was complied with no errors.
    However, that routine is also commented out and shouldn't be related to my problem
     
  6. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
  7. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #7
    here is the entire p1640.h
    Code:
    #define fpsize 2048
    #define lenslets_size  250
    #define imagesize (lenslets_size*lenslets_size)
    #define centersize  407
    #define low_res 25
    #define high_res 67
    #define magnifyfpfactor 3
    #define pixelsperlenset 10.568  
     //lenslet rotation 
    #define sinr .322 
    #define cosr .947
    
    #define mag 10.568
    #define waves 23
    
    #define no 0
    #define yes 1
    //#define psfdir	"/extract/psfs/"
    #define psfdir "/proj1640_pipeline-debug5/library/laser/psf/"
    #define psf24dir "/data/psfs24/"
    
    #define psf30dir "/data/psfs30/"
    #define psfalldir "/proj1640_pipeline-debug5/library/laser/psfall/"
    #define mapdir  "/data/maps25/"
    
    #define data "/DATA/"
    #define filtersize  15
    #define fwhm1 5
    #define fwhm2 16
    #define processed_data "/data/processed/"
    
    #define sizeofcube lenslets_size*lenslets_size*waves
    
    #define MAXAXES   3     
    
    #include "/cfitsio/include/fitsio.h"
    #include "/cfitsio/include/fitsio2.h"
    #include "/cfitsio/include/longnam.h"
    #include <fcntl.h>
    #include <unistd.h>
    #include <math.h>
    #include <sys/types.h>
    #include <dirent.h>
    #include <string.h>
    
    
    
    
    
    float * opencube (char *av);
    float * makefilter();
    long naxis;
    long naxes[MAXAXES];
    int ndatas;
    int row, col,fpcol, fprow;
    
    
    
    void ludcmp( float **a, int n, int *indx, float *d);
    void lubksb(float **a, int n, int *indx, float b[]);
    void inverse(float  **a, float **b, int N);
    float ** MatrixMult(float **a, float **b, int N);
    float ABAT(float **a, float *b, int n);
    
    int findlaserspots(char * infile, char * outfile);
    int makelaserpsf(char * spotfile, char *infile, char * outfile);
    int centroidpsfs (char * spotfile, char * psffile);
    void makefilters(int* fpcols, int* fprows,float ** spots, int col, int row);
    //char *laserdirectory, *cmd1, *codedirectory,*psfdirectory,*darkdirectory, *infile1, *outfile1, *spotfile1, *spotsdirectory ;
    //char  *cmd2,  *infile2, *outfile2, *spotfile2 ;
    
    
    
    void spline(float x[], float y[], int n, float yp1, float ypn, float y2[]);
    void splint(float xa[], float ya[], float y2a[], int n, float x, float *y);
    void splie2 (float x1a[], float x2a[], float **ya, int m, int n, float **y2a);
    void splin2(float x1a[], float x2a[], float **ya, float **y2a, int m, int n, float x1, float x2, float *y);
    
    
    float * load_simple_fits_float_data(char *fn, long *naxis, long *naxes, int *ndatas);
    int write_simple_fits_float_data(char *fn, long naxis, long *naxes, float *dbuf);
    static void printerror(const char *msg, int status);
    
    
    float * load_simple_fits_float_data(char *fn, long *naxis, long *naxes, int *ndatas)
    {
    	int DEBUG = 0;
        fitsfile   *fptr;        /* fits ptr    */
        int        status=0;
        long       nelem;
    	
        char       cmnt[128];
    	
        float      nullval = 0.0;    /* fits arcanum */
        int        anynull = 0;    /* fits arcanum */
    	
    	
        const char        *axisname[7] = { "NAXIS1",  "NAXIS2",  "NAXIS3",  
    		"NAXIS4",  "NAXIS5",  "NAXIS6",  "NAXIS7" };
        int        i;
        float      *ldbuf;        /* local space */
    	if(DEBUG)
    		printf("%s\n", "0");	
    
    	
        /* Open fits file... */
        if (fits_open_file(&fptr, fn, READONLY, &status)) {
            printerror("load_simple_fits_float_data: fits_open_file: ", status);
            return NULL;
        }
    	if(DEBUG)
    		printf("%s\n", "A");	
        /* get a few keywords */
    	
        /* find image dimensionality */
        if (fits_read_key(fptr, TLONG, "NAXIS", naxis, cmnt, &status)) {
            printerror("load_simple_fits_float_data: fits_read_key: NAXIS", status);
            return NULL;
        }
        /*(void) fprintf(stderr, "    NAXIS = %d\n", (int) *naxis);*/
    	if(DEBUG)
    		printf("%s\n", "B");
    	
        /* find image size for as many axes as exist */
        for (i=0, nelem=1; i<*naxis; i++) {
            if (fits_read_key(fptr, TLONG, axisname[i], naxes+i, cmnt, &status)) {
    			printerror("load_simple_fits_float_data: fits_read_key:",
    					   status);
    			return NULL;
            }
            /*(void) fprintf(stderr, "    %s = %d\n", axisname[i],  (int) naxes[i]);*/
            nelem *= naxes[i];
        }
        
    	if(DEBUG)
    		printf("%s\n", "b");
    	if (*naxis > MAXAXES) {
            /*(void) fprintf(stderr, "    %d axes > allowable dimensionality (%d)\n", (int) *naxis, MAXAXES);*/
            return NULL;
    	}
    	
    	if(DEBUG)
    		printf("%s\n", "C");
    	
        /* (void) fprintf(stderr, "    There are %d pixels in %s, %d * %d is %d\n", (int)nelem, fn,
    	 (int)naxes[0], (int)naxes[1],  (int)(naxes[0] * naxes[1])); */
    	
    	
        /* allocate zeroed space for data in the buffer ptr ldbuf */
        if ((ldbuf = (float *) calloc(nelem, sizeof(float))) == NULL) {
            (void) fprintf(stderr, "load_simple_fits_float_data: Out of mem for ldbuf\n");
            return NULL;
        }
    	if(DEBUG)
    		printf("%s\n","D");
    	if (fits_read_img(fptr, TFLOAT, (long)1, nelem, &nullval,
    					  ldbuf, &anynull, &status)) {
            printerror("load_simple_fits_float_data: fits_read_image:",
    				   status);
            return NULL;
        }
    	if(DEBUG)
    		printf("%s\n", "E");
    	
        /* close the table */
        if (fits_close_file(fptr, &status)) {
            printerror("load_simple_fits_float_data: fits_close_file: ", status);
            return NULL;
        }
    	
    	*ndatas = (int)nelem;
    	if(DEBUG)
    		printf("%s\n", "F\n");
    	
        return ldbuf;
    }
    
    int write_simple_fits_float_data(char *fn, long naxis, long *naxes, float *dbuf)
    {
    	
        fitsfile   *fptr;        /* fits ptr    */
        int        status=0;
        long       nelem;
        long       fpixel=1;
    	
        char       cmnt[128];
    	
    	float       meaning = 42.0;
        int        i;
    	
     //   (void) printf("    NAXIS = %d\n", (int) naxis);
    	nelem = 1;
    	for (i=0; i<naxis; i++) {
    		nelem *= naxes[i];
        	(void) printf("%d.", (int) naxes[i]);
    	}
        (void) printf(" = %d pixels\n", (int) nelem);
    	
    	
    	/* open up a fits file handle.. */
    	if (fits_create_file(&fptr, fn, &status)) {
    		printerror("write_simple_fits_float_data: fits_create_file: ", status);
    		return -1; 
    	}
    	
    	
        /* Create fits file... */
        if (fits_create_img(fptr, FLOAT_IMG, naxis, naxes, &status)) {
    		printerror("write_simple_fits_float_data: fits_create_file: ", status);
    		return -1; }
    	
        /* set a keyword value for fun */
    	strcpy(cmnt, "Life, the Universe and everything");
        if (fits_update_key(fptr, TFLOAT, "LUNVNVRT", &meaning, cmnt, &status)) {
            printerror("write_simple_fits_float_data: fits_update_key: NAXIS", status);
            return -1;
        }
    	
    	
        /* dump data to fits file */
        if (fits_write_img(fptr, TFLOAT, fpixel, nelem, dbuf, &status)) {
            printerror("write_simple_fits_float_data: fits_write_file: ", status);
            return -1;
        }
    	
    	
        /* close the fits file */
        if (fits_close_file(fptr, &status)) {
            printerror("write_simple_fits_float_data: fits_close_file: ", status);
            return -1;
        }
    	return nelem;
    	
    }
    
    
    static void printerror(const char *msg, int status) {
    	
        if (status != 0) {
            fprintf(stderr, "%s ", msg);
            fits_report_error(stderr, status);
        }
    }
    
    
     
  8. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #8
    found the error. Its amazing how obvious some of these errors are after the fact. datadir wasn't being freed.

    Now why doesn't my system call to cd work?
     
  9. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #9
    The "system" call starts a "shell", asks it to change its current directory and then the "shell" exits.

    I think you're wanting "chdir" instead!

    EDIT: Forget that I think you're wanting to combine both "system" calls into one along the lines of:

    strcpy(cmd, "cd ");
    strcat(cmd, datadir);
    strcat(cmd, ";");
    strcpy(cmd, "ls ");
    strcat(cmd, datadir);
    strcat(cmd, "/*.fits ");
    strcat(cmd, "> filelist.lis");
    system(cmd);
     
  10. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #10
    Which I could say you were right but it didn't work.
     
  11. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #11
    Oh it works its just that it's not all happening in the directories you believe you specifying.

    What is showing when you print the contents of "datadir".
     
  12. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #12
    I don't think an unfreed datadir, by itself, can fully account for the original error.

    Not freeing a block of calloc'ed memory merely consumes memory in that process (a memory leak). It does not directly or indirectly cause any kind of other errors, certainly not segmentation errors. Not freeing datadir leaks 200 bytes. I find it hard to believe that's significant.

    It may well be that other changes you made, in addition to freeing datadir, are what fixed the error.

    For example, one other latent error is the cmd array is only 100 bytes long, yet datadir is calloc'ed at 200 bytes. So if datadir is even half full, then cmd will be overrun when it's strcat'ed into.

    Another error is this:
    which is going to print garbage at best, and may well overrun the uninitialized cmd array at worst. In fact, that may even be the cause of the original segv error, if we assume the command-line args are short enough to not overrun any buffers.

    Finally, most of these errors are data-dependent. They will definitely fail if the command-line args are long enough. They will just as definitely succeed if the command-line args are short enough. So it's not always enough to post code. It's also necessary to provide example inputs that cause the failure.
     
  13. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #13
    The printf statement printed and I do not have string over run problems.
     
  14. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #14
    farmerdoug,

    Use spotlight to search for your "filelist.lis" file. I believe you'll find that is was created, just not where you're thinking is should be!
     
  15. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
  16. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #16
    For the current running application (that's your program) use a call to 'chdir'. But there is a problems with that in that what your developing is command line tool. Once you move form the testing environment (Xcode) to deployment that call may no longer be needed.
     
  17. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #17
    Except that since Xcode won't use my cfitsio library, I compile with a make file and test on the command line.
     
  18. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #18
    We're all over the board here; focus is in verrrrry short supply!

    I really don't know where to continue from here.
     
  19. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #19
    You mean I don't get your undivided attention. LOL.
     
  20. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #20
    Not even if you were paying me!

    How do you wish to proceed?
     
  21. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #21
    If you have any good ideas let me know; If I get a solution, I'll let you know.
     
  22. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #22
    Here's how its done.

    You use chdir. Its a function and not used as in a system call. However, and here's the catch, the directory is changed in the program not in the terminal.
    When I use cd in iraf, after I exit the program, I am in the new directory. That doesn't happen in C but the program does act in the dir you changed to.
    (note:) definitely need unistd.h and stdlib here. Not sure about the others.

    Code:
    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/dir.h>
    #include <sys/param.h>
    #include <stdlib.h>
    
    int main (int argc, const char * argv[]) {
        // insert code here..
    	char pathname[10];
    	
        chdir ("/data");    // change directory
    	getwd(pathname); // get pathname.
    	printf("%s\n", pathname);
    	system( "ls > tmp.txt");
    	return 0;
    }
    
     
  23. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #23
    This is standard Posix behavior (it's standard in Windows, Linux, and many others, too). chdir applies to the current process. It is also inherited by any child processes spawned by that process, but it has no effect on any other process, including prevouslyt spawned children that are still running. Each child process, in turn, can chdir() itself under the same rules.

    You might have to explain what iraf is.

    When you use cd in a typical shell or other command interpreter, the shell executes chdir in its own process, rather than spawning a child process. For the reasons outlined above.
     
  24. farmerdoug thread starter macrumors 6502a

    Joined:
    Sep 16, 2008
    #24
    Thanks for the info.

    IRAF is the Image Reduction and Analysis Facility, a general purpose software system for the reduction and analysis of astronomical data.
     

Share This Page