gpt4 book ai didi

C 程序中的编译错误返回整数输入序列中出现次数最多的整数

转载 作者:行者123 更新时间:2023-11-30 20:37:09 26 4
gpt4 key购买 nike

我有一个 C 程序,它读取非负整数序列,并打印该序列两次,每行一个元素。要求输入包含的整数不超过 1000 个。我使用一个名为 getint() 的模块来代替 scanf,该模块读取整数输入,如果读取到 -1 或 EOF,则程序结束。我收到几个编译错误,我认为这是由于我的代码试图访问超出范围的数组索引所致。有人可以帮助我吗,因为我真的不知道如何解决它。

// ar_max(a[]) returns the max entry of a

int ar_max(int a[]) {

int max_so_far = a[0];

for (int i = 1; i < 1000; i++) {

if (a[i] > max_so_far) {

max_so_far = a[i];
}
}
return max_so_far;
}


int main() {

int inputnum = getint();

// array containing the distinct numbers seen

int a_num[1000] = {};

// array containing the frequencies of the distinct numbers seen

int a_freq[1000] = {};

int len_n;

while (inputnum != -1) {

int i = 0;

len_n = i + 1;

//int len_f = i;

// update the frequency of inputnum if it's already been seen

for (i = 0; i < len_n; i++, len_n = i+1) {

if (a_num[i] == inputnum) {

a_freq[i] = a_freq[i] + 1;

}

}

// add inputnum into the array if it hasn't already been seen

if (i == len_n) {

a_num[i+1] = inputnum;

a_freq[i+1] = 1;

}

inputnum = getint();

}

// print the first number with the highest frequency

for (int j = 0; j < len_n; j++) {

if (a_freq[j] == ar_max(a_freq)) {

printf("%d\n", a_num[j]);

break;

}

}

}

编译错误是:

Stack buffer overflow on address 0x7fff88d20050. Check array indices.
Error caused by read of size 4 byte(s) to 0x7fff88d20050:
frame 0: main, freq.c:37:11
frame 1: __libc_start_main, libc-start.c:226:0
frame 2: _start, from module A6-getint.c-g38-binary (+0x41ba94)

0x7fff88d20050 is contained 4064 bytes into stack frame:
frame 0: main, freq.c:24:0

This frame has 7 object(s):
4 byte object inputnum located 48 bytes into frame.
4000 byte object a_num located 64 bytes into frame. Access overflew this variable.
4000 byte object a_freq located 4192 bytes into frame.
4 byte object len_n located 8320 bytes into frame.
4 byte object i located 8336 bytes into frame.
4 byte object j located 8352 bytes into frame.
Program finished with exit code 1 (An error occurred).

最佳答案

这些不是编译错误,而是运行时错误。

是的,您认为这一定是数组边界问题是正确的。第 37 行崩溃的唯一方法是 j>1000

我发现你没有初始化 len_n,如果你从不进入 while 循环(意味着 inputnum 立即返回 -1),那么 j 可能会在后一个循环中超过 1000。

关于C 程序中的编译错误返回整数输入序列中出现次数最多的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com