By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 811 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

char pointer array problem

P: 6
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.

Expand|Select|Wrap|Line Numbers
  1. int readlines(char *lineptr[], int maxlines)
  2. {
  3.         int len, nlines,i;
  4.         char *p, line[MAXLEN];
  5.  
  6.         len=0;
  7.         nlines=0;
  8.  
  9.         while( (len=getline(line,MAXLEN)) > 0)
  10.         {
  11.                 printf("len=%d\n",len);
  12.                 if(nlines >= maxlines)
  13.                         return -1;
  14.                 else if( (p=(char *) malloc(sizeof(len+1))) == NULL )
  15.                         return -1;
  16.                 else
  17.                 {
  18.                         line[len]='\0';
  19.                         strcpy(p,line);
  20.                         //lineptr[nlines]=(char *)malloc(sizeof(len));
  21.                         lineptr[nlines]=p;
  22.                         nlines++;
  23.                 }
  24.                 //free(p);
  25.         }
  26.  
  27.         printf("printing values of pointer lines in readlines() \n");
  28.         for(i=0;i<nlines;i++)
  29.     {
  30.                 printf(lineptr[i]);
  31.                 printf("\n");
  32.         }
  33.         //free(p);
  34.         return nlines;
  35. }
The single line comment in the code is what I'm not sure if I should do tht.
Thank you.
Nov 2 '06 #1
Share this Question
Share on Google+
1 Reply


Banfa
Expert Mod 5K+
P: 8,916
You do not need either of the commented out lines, the problem is with this line

else if( (p=(char *) malloc(sizeof(len+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).
Nov 2 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.