C中的双重释放或损坏(fasttop)错误/分段错误 [英] double free or corruption(fasttop) error/segmentation fault in C

查看:74
本文介绍了C中的双重释放或损坏(fasttop)错误/分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态分配一个数组以从命令行读取用户输入.它可以工作 99/100 次,但是如果我重复输入一堆字符,我有时会收到分段错误错误或双重释放或损坏(fasttop)错误.这个错误比较难重现.

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;
    }

推荐答案

代码似乎正在尝试使用 "%s" 打印一个 char 数组而不是一个细绳.缺少空字符 '\0' 终止.

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

问题也可能出现在 processOptions() 中,因为该函数调用没有传递有效数据的长度.

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);

<小时>

注意:无限循环应该getc(stdin)返回EOF.更好用

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

这篇关于C中的双重释放或损坏(fasttop)错误/分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆