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