gpt4 book ai didi

c - GDB 挂起 - 不明白为什么

转载 作者:行者123 更新时间:2023-11-30 15:29:56 25 4
gpt4 key购买 nike

我正在阅读《C 编程语言》一书,并完成所有示例,并在 GDB 中进行探索,看看发生了什么。

在下面的示例代码中,目标是评估几行文本以确定哪一行是最长的行。我认为我自己的程序失败了,因为 gdb 卡在调用 getchar() 的 for 循环中。我跟踪回溯,找到了罪魁祸首,但无法确定确切的问题。然后我对示例代码执行了相同的操作,并且在调用 getchar()for 循环中出现了完全相同的问题。

// file: ch1/ex16.c
// OBJECTIVE: Revise the main routine o the lnogest program
// so it will correctly print the length of arbitrarily long
// lines and as much as possible of the text.

#include <stdio.h>

#define MAXLINE 1000

int getLine(char line[], int maxline);
void copy(char to[], char from[]);

int main()
{
int len, max;
char line[MAXLINE], longest [MAXLINE];

max = 0;
while ((len = getLine(line, MAXLINE)) > 0) {
if (len > max) {
max = len;
copy(longest, line);
}
}

if (max > 0) {
printf("%s", longest);
}

return 0;
}

int getLine(char s[], int lim)
{
int c, i;

for (i=0; i < lim - 1 && (c=getchar()) != EOF && c != '\n'; ++i) {
s[i] = c;
}
if (c == '\n') {
s[i] = c;
++i;
}
s[i] = '\0';

return i;
}

void copy(char to[], char from[])
{
int i = 0;

while ((to[i] = from[i]) != '\0'){
++i;
}
}

最佳答案

与通过 shell 执行程序不同,gdb不接受 ^d (ctrl+d) 作为 EOF。感谢上面 Duck 提供的评论,我发现如果我通过标准输入给它提供一个文件 gdb它解决了问题。

例如:

(gdb)运行<文件.txt

关于c - GDB 挂起 - 不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25954036/

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