java从控制台读取数据到数组,从控制台读取字符并存储在数组中时,为什么会出现分段错误?...

我正在尝试编写一个程序,将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 ***

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值