gpt4 book ai didi

c - C 中的双重释放或损坏(fasttop)错误/段错误

转载 作者:行者123 更新时间:2023-11-30 15:24:59 28 4
gpt4 key购买 nike

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

我很确定错误的发生是由于我重新分配数组的方式造成的。

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' 终止符。

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

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 - C 中的双重释放或损坏(fasttop)错误/段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28131466/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com