char *dumpTB (TB tb){
char* text = malloc(sizeof(char));
int i = 0; //
int x = 0; //string index
tNode* curr = tb->head;
while(curr != NULL){
while(curr->line[x] != '\n'){
printf("%d", i);
text[i] = curr->line[x];
printf("%c\n", text[i]);
text = realloc(text, i+1);
i++;
x++;
}
text[i] = '\n';
printf("%c", text[i]);
text = realloc(text, i+1);
i++;
x = 0;
curr = curr->next;
}
return text;
}
所以我设法使用print语句打印出我的字符串的前12个字母但由于某种原因它在打印第12个字母'l'后不久给我一个seg错误,并且基于打印语句它似乎发生在realloc周围......谁能告诉我我做错了什么?
int i = 1; //
int x = 0; //string index
tNode* curr = tb->head;
while(curr != NULL){
while(curr->line[x] != '\n'){
printf("%d", i-1);
text[i-1] = curr->line[x];
printf("%c\n", text[i-1]);
text = realloc(text, i+1);
i++;
x++;
}
printf("%d\n", i-1);
text[i-1] = '\n';
printf("%c", text[i-1]);
text = realloc(text, i+1);
i++;
x = 0;
curr = curr->next;
//printf("%c\n", curr->line[0]);
}
我尝试修复了索引错误,这是一个非常长的sysmalloc断言事件,它会中止程序。
你可能想要getline(3),所以use它,如果你有它。正如AnT's answer所解释的那样,由于undefined behavior,你有buffer overflow(UB)。尽快解决这个问题。是UB的scared,花更多的时间来阅读它(这很棘手)。
此外,请记住,malloc(3)和realloc(3)都是某种昂贵的电话(对于一些合适的昂贵概念;实际上,它们非常快 - 在桌面上通常不到一微秒才能合理使用),并且它们可能会失败(通过给予NULL
)和你应该check。
在实践中,你最好不要经常使用realloc
。根据经验,您希望在某处保留使用的长度和分配的大小(例如,在其他局部变量中),并且您可以使用一些几何级数(例如newsize = 4*oldsize/3 + 10
....)来避免过于频繁的realloc
-s。为每个额外的字节做一个realloc
很难看。
使用所有警告和调试信息编译代码,例如: gcc -Wall -Wextra -g
与GCC。改进代码以获得警告。 Use the debugger gdb
和valgrind打猎memory leaks和其他麻烦。