double free or corruption(fasttop) error/segmentation fault in C

醉酒当歌 提交于 2019-12-12 03:17:29

问题


I'm trying to dynamically allocate an array to read user input from the command line. It works 99/100 times, but if I type in a bunch of characters repeatedly I will sometimes get a segmentation fault error OR a double free or corruption(fasttop) error. This error is relatively hard to reproduce.

I'm pretty sure the error occurs because of the way I'm reallocating the array.

while(1){
        char *buf_in;               // Holds user keyboard input
        int cnt = 0, length = 0;    // cnt stores current read buffer size, length allows input into buf_in
        char ch;
        int buf_max = 64;           // Current buffer size. Dynamically allocated

        buf_in = malloc(buf_max * sizeof(char));
        if (buf_in==NULL){
            fprintf(stderr,"Error allocating memory!\n");
            exit(EXIT_FAILURE);
        }

        do{
            if (cnt > (buf_max/2)){
                cnt = 0;
                buf_max *= 2; // Double size of buffer
                printf("Doubling buffer: %d\n",buf_max);
                buf_in = realloc(buf_in,buf_max);
                if (buf_in == NULL){
                    fprintf(stderr,"Error re-allocating memory!\n");
                    exit(EXIT_FAILURE);
                }
            }
            /* Store line-by-line into buffer */
            ch = getc(stdin);
            buf_in[length] = ch;
            length++;
            cnt++;
        }while(ch != '\n');

        /* Handles different option arguments */
        processOptions(buf_in,&opt_n_inc);

        // stdout
        fprintf(stdout,"%s",buf_in);
        fflush(stdout);

        free(buf_in);
        buf_in=NULL;
    }

回答1:


Code appears to be attempting to print using "%s" an array of char and not a string. The null character '\0' termination is missing.

Also the problem may be manifesting itself in processOptions() as that function call does not pass the length of valid data.

buf_in[length] = ch;

// Add    
buf_in[length+1] = '\0';

...
processOptions(buf_in,&opt_n_inc);
fprintf(stdout,"%s",buf_in);

Note: infinite loop should getc(stdin) return EOF. Better to use

int ch = getc(stdin);
if (ch == EOF) break;
buf_in[length] = ch;


来源:https://stackoverflow.com/questions/28131466/double-free-or-corruptionfasttop-error-segmentation-fault-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!