C中的双重自由或损坏(快速顶部)错误/分段错误

我正在尝试动态分配一个数组来从命令行读取用户输入。 它可以工作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; } 

代码似乎试图使用"%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;