奇怪的seg故障,可能与realloc

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) ,所以如果你有它,请使用它。 正如AnT的回答所解释的那样 ,由于缓冲区溢出 ,您有未定义的行为 (UB)。 尽快解决这个问题。 非常害怕 UB并花更多时间阅读它(这很棘手)。

另外,请记住malloc(3)和realloc(3)都是某种昂贵的调用(对于某些合适的昂贵概念;实际上,它们非常快 – 在桌面上通常不到一微秒才能合理使用),并且它们可能会失败(通过给出NULL )你应该检查一下。

在实践中,您最好realloc经常使用realloc 。 根据经验,您希望将使用的长度和分配的大小保持在某处(例如,在其他局部变量中),并且您可以使用一些几何级数(例如newsize = 4*oldsize/3 + 10 ….)避免过于频繁的realloc -s。 对每个附加字节执行重新分配是很难看的。

使用所有警告和调试信息编译代码,例如gcc -Wall -Wextra -g和GCC 。 改进代码以获得警告。 使用调试器 gdb和valgrind来捕获内存泄漏和其他麻烦。