strange seg fault, likely with realloc

后端 未结 1 1553
南笙
南笙 2021-01-29 13:23
char *dumpTB (TB tb){

    char* text = malloc(sizeof(char));

    int i = 0; // 
    int x = 0; //string index

    tNode* curr = tb->head;

    while(curr != NULL){         


        
相关标签:
1条回答
  • 2021-01-29 13:53

    You probably want getline(3), so use it if you have it. As explained by AnT's answer, you have undefined behavior (UB) because of a buffer overflow. Fix that as soon as possible. Be very scared of UB and take more time to read about it (it is tricky).

    Also, remember that both malloc(3) and realloc(3) are somehow expensive calls (for some suitable notion of expensive; actually, they are quite fast - often less than a microsecond on a desktop for reasonable use), and they could fail (by giving NULL) and you should check that.

    In practice, you'll better use realloc less often. As a rule of thumb, you want to keep both the used length and the allocated size somewhere (e.g. in additional local variables), and you might use some geometrical progression (e.g. newsize = 4*oldsize/3 + 10....) to avoid too frequent realloc-s. Doing a realloc for each additional byte is ugly.

    Compile your code with all warnings and debug info, e.g. gcc -Wall -Wextra -g with GCC. Improve the code to get no warnings. Use the debugger gdb and valgrind to hunt memory leaks and other trouble.

    0 讨论(0)
提交回复
热议问题