我正在尝试编写一个程序,它将字符从标准输入读取到字符数组中,这样我就可以对该数组执行其他操作。我编写了程序,以便在需要时为数组动态分配更多内存。但是,一旦我结束程序的输入,我总是会遇到分段错误。
笔记:
- 我使用 int 而不是 char 来存储正在读取的字符,所以我相信与 EOF 的比较应该是有效的?
- 这
ch == 'l'
条线就在那里,因为我厌倦了按两次 Ctrl+D,一旦我解决了这个问题,它就会被删除。
以下是在 main 中,在程序开头带有 stdlib/stdio #included:
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()) != '\0' && 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) = %d\n", arrCount, ch, sizeof(ch));
input[arrCount++] = ch;
printf("&input[%d] = %p\n", arrCount-1, &input[arrCount - 1]);
printf("input[%d] = %c\n", arrCount - 1, input[arrCount - 1]);
if (ch == 'l') {
break;
}
}
示例输出:
... $ ./db
输入是一个包含 200 个字符的数组,占用 200 个字节。
tl
arrCount = 0; ch = t; sizeof(ch) = 4
&输入[0] = 0x827a008
输入[0] = t
输入[0] = t
arrCount = 1; ch = l; sizeof(ch) = 4&输入[1] = 0x827a00a
输入[1] = l
输入[1] = t
分段故障
可能与此相关的其他内容:我注意到如果我为输入数组输入了足够的字符以达到索引 399 / 大小 400,也会弹出此错误:
*** glibc detected *** ./db: realloc(): invalid old size: 0x08a73008 ***