【发布时间】:2026-01-26 08:00:02
【问题描述】:
我正在编写代码来查找输入流中最长的行并将其打印出来。但是,在我定义了一个名为max_count = 0的int之后,我总是发现一个溢出,它显示max_count为1633771873。我已经初始化了那个变量,所以我不知道问题出在哪里。您可能不需要弄清楚所有功能,但每个功能都有其注释。
这是我的代码:
#include <stdio.h>
#define DEFAULT 10
int getline(char line[], int limit);
void copy(char from[], char to[]);
int enlarge(int lim, char s[]);
main()
{
int i;
int max_count = 0;
char line[DEFAULT];
char maxline[DEFAULT];
while ((i = getline(line, DEFAULT)) != 0) {
if (i > max_count) { // where weird thing happend (max_count=1633771873)
max_count = i;
copy(line, maxline);
}
}
if (max_count > 0) {
printf("maxline: %s", maxline);
} else {
printf("No maxline");
}
return 0;
}
/*get a row from input stream and return its length*/
int getline(char s[], int lim)
{
int i, c;
for (i = 0; ((c = getchar()) != EOF) && (c != '\n'); ++i) {
if (i == lim - 1) {
lim = enlarge(lim, s);
}
s[i] = c;
}
if (c == '\n') {
s[i] = c;
++i;
}
if (i == lim) {
enlarge(lim, s);
}
s[i] = '\0';
return i;
}
/*copy an array to another */
void copy(char from[], char to[])
{
int i = 0;
while (from[i] != '\0') {
to[i] = from[i];
++i;
}
}
/*expand an array twice as its capacity*/
int enlarge(int lim, char s[])
{
s[lim - 1] = '\0';
lim *= 2;
char temp[lim];
copy(s, temp);
s = temp;
return lim;
}
这是控制台窗口:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
^Z
maxline:
--------------------------------
Process exited after 15.19 seconds with return value 3221225477
【问题讨论】:
-
returns 3221225477- 你的意思是 printsmaxline: 3221225477?请发布您的程序的输出。请将输入发布到您的程序中。 -
确实如此。这个程序不打印 max_count 那么你怎么知道 max_count 有什么值呢?你在用调试器吗? (没关系,但如果是,请说出来)
-
如何神奇地将阵列扩展至其容量的两倍?它的长度是
10,就是这样。您必须使用malloc和realloc来执行此操作。 -
@user253751,是的,我使用了调试器,它告诉我这个值
-
碰巧你的十六进制“溢出值”是
61616161,这是'a'的ASCII值。你有缓冲区溢出。