c - Dynamic 2D array crashes -


i reading file (each line wolds 1 word) , putting each line array. crashes when close file saying (* glibc detected * proj: corrupted double-linked list: 0x0000000002139240 ***). 1st element copied correctly (the 1st element supposed "how you" instead "0"). on appreciated.

int = -1; int numb; int wsize;  while (fgets(word,30,file)!=null) {     if (i==-1)     {          if(word[strlen(word)-1]=='\n')          {              word[strlen(word)-1] = 0;          }          numb = atoi(word);          ptr = malloc(sizeof(char*)*numb);     }     else     {         if(word[strlen(word)-1]=='\n')         {              word[strlen(word)-1] = 0;         }         wsize = strlen(word);         ptr[i] = malloc(sizeof(char*)*wsize);         strncpy(ptr[i],word,strlen(word));         size++;      }      i++; } int j=0; while(j<16)     //prints see if copied corectly {               //ptr[0] 1 did not copy corectly     printf("%s\n",ptr[j]);            j++; } fclose(file); printf("test\n"); //was never printed assume crashes @ fclose() return 1; 

the line ptr[i] = malloc(sizeof(char*)*wsize); wrong, 2 reasons:

  1. it should sizeof(char), not sizeof(char*) (or omit this, since sizeof(char) equal 1 definition)

  2. if want store string of length wsize, need allocate wsize+1 bytes

edit — more issues:

  1. what purpose of line size++;? did mean wsize++;?

  2. where number 16 come in while(j<16)? suggest try while(j<i) instead.

  3. if main() returns nonzero value, signifies error occurred. change return 0; unless have reason returning other value.

one more:

  1. i noticed you're using strncpy(). won't add terminating '\0' byte end of string because you've asked copy string of length wsize using no more wsize bytes. change line strcpy(ptr[i],word); , should work.

after you've done that, need remove potential buffer overflows code. (there lots of them.)


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -