我正在尝试动态分配数组以从命令行读取用户输入。它可以工作99/100次,但是如果我反复键入一堆字符,我有时会遇到分段错误错误或双重自由或损坏(快速顶部)错误。此错误相对难以重现。
由于我正在重新分配数组的方式,我很确定会发生错误。
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;
}
答案 0 :(得分:1)
代码似乎试图使用"%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;