char pointer array problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyCGal
    New Member
    • Oct 2006
    • 6

    char pointer array problem

    Hi,

    I have this code I wrote to copy any length lines into array of pointers. The problem is after storing the individual lines into the char pointer array, the dispaly() chops off some lines while retains the others (mostly last and first line in the array). I guess there is some allocation problem but don't know where exactly.

    Please suggest.

    Code:
    int readlines(char *lineptr[], int maxlines)
    {
            int len, nlines,i;
            char *p, line[MAXLEN];
    
            len=0;
            nlines=0;
    
            while( (len=getline(line,MAXLEN)) > 0)
            {
                    printf("len=%d\n",len);
                    if(nlines >= maxlines)
                            return -1;
                    else if( (p=(char *) malloc(sizeof(len+1))) == NULL )
                            return -1;
                    else
                    {
                            line[len]='\0';
                            strcpy(p,line);
                            //lineptr[nlines]=(char *)malloc(sizeof(len));
                            lineptr[nlines]=p;
                            nlines++;
                    }
                    //free(p);
            }
    
            printf("printing values of pointer lines in readlines() \n");
            for(i=0;i<nlines;i++)
    	{
                    printf(lineptr[i]);
                    printf("\n");
            }
            //free(p);
            return nlines;
    }
    The single line comment in the code is what I'm not sure if I should do tht.
    Thank you.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You do not need either of the commented out lines, the problem is with this line

    else if( (p=(char *) malloc(sizeof(l en+1))) == NULL )

    You are allocating sizeof(len+1) bytes, len is an int and so in len+1 so you are allocating sizeof(int) bytes (typically 2 or 4).

    Comment

    Working...