我正在尝试编写一个程序,将stdin中的字符读入字符数组,这样我就可以对该数组执行其他操作 . 我编写了程序,以便在需要时为数组动态分配更多内存 . 但是,一旦我结束程序的输入,我总是会遇到分段错误 .
笔记:
我使用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&input [0] = 0x827a008 input [0] = t input [0] = t arrCount = 1; ch = l; sizeof(ch)= 4&input [1] = 0x827a00a input [1] = l input [1] = t分段错误
可能与此相关的其他内容:我注意到如果我为输入数组输入足够的字符以获得索引399 /大小400,则此错误也会弹出:
*** glibc detected *** ./db: realloc(): invalid old size: 0x08a73008 ***