c-为什么我在从控制台读取字符并存储在数组中时会出现分段错误



我正试图编写一个程序,将stdin中的字符读取到字符数组中,这样我就可以对该数组执行其他操作。我编写了这个程序,以便在需要时为数组动态分配更多内存。然而,一旦我结束程序的输入,我总是会遇到分段错误。

注:

  • 我使用int而不是char来存储读取的字符,所以我认为与EOF的比较应该有效吗
  • ch == 'l'行就在那里,因为我厌倦了按Ctrl+D两次,一旦我解决了这个问题,它就会被删除

以下内容在main中,stdlib/stdio#包含在程序的开头:

int arrCount = 0, arrSize = 200, ch, key_data_len;
char* input = malloc(arrSize * sizeof(char));
printf("Input is an array of %d characters that takes up %d bytes.n", arrSize, arrSize * sizeof(char));
// Add characters to array until input is finished.
while ( (ch = (int) getchar()) != '' && ch != EOF) {
  if(arrCount >= arrSize)
  { 
    printf("GOT IN IF STATEMENT.");
    // If the array has not been initialized, fix that.
    if (arrSize == 0)
      arrSize = 200 * sizeof(char);
    // Make the reallocation transactional by using a temporary variable first
    char *_tmp = (char *) realloc(input, (arrSize *= 2));
    // If the reallocation didn't go so well, inform the user and bail out
    if (!_tmp)
    {
      fprintf(stderr, "ERROR: Couldn't realloc memory!n");
      return(-1);
    }
    // Things are looking good so far
    input = _tmp;
  }
  printf("narrCount = %d; ch = %c; sizeof(ch) = %dn", arrCount, ch, sizeof(ch));
  input[arrCount++] = ch;
  printf("&input[%d] = %pn", arrCount-1, &input[arrCount - 1]);
  printf("input[%d] = %cn", arrCount - 1, input[arrCount - 1]);
  if (ch == 'l') {
    break;
  }
}

示例输出:

…$/db

输入是一个由200个字符组成的数组,占用200个字节。

tl

arrCount=0;ch=t;尺寸(ch)=4

&input[0]=0x827a008

input[0]=t

input[0]=t


arrCount=1;ch=l;尺寸(ch)=4

&input[1]=0x827a00a

input[1]=l

input[1]=t

分段故障

可能与此相关的其他事情:我注意到,如果我为输入数组输入了足够的字符,以达到索引399/大小400,也会弹出此错误:

*** glibc detected *** ./db: realloc(): invalid old size: 0x08a73008 ***

这是错误的,您正在释放刚刚分配的数组:

input = _tmp;
free(_tmp);

你根本不需要free——realloc为你做这件事。

最新更新