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:
it should
sizeof(char), notsizeof(char*)(or omit this, sincesizeof(char)equal 1 definition)if want store string of length
wsize, need allocatewsize+1bytes
edit — more issues:
what purpose of line
size++;? did meanwsize++;?where number 16 come in
while(j<16)? suggest trywhile(j<i)instead.if
main()returns nonzero value, signifies error occurred. changereturn 0;unless have reason returning other value.
one more:
- i noticed you're using
strncpy(). won't add terminating'\0'byte end of string because you've asked copy string of lengthwsizeusing no morewsizebytes. change linestrcpy(ptr[i],word);, should work.
after you've done that, need remove potential buffer overflows code. (there lots of them.)
Comments
Post a Comment