gpt4 book ai didi

c - 分解循环的结束条件

转载 作者:太空宇宙 更新时间:2023-11-04 07:33:35 25 4
gpt4 key购买 nike

晚上好

我在做作业时遇到了问题。

基本上我们需要编写一个程序来计算给定 stdin 的质因数.数据只能通过其stdin进入程序。 , 通过 echo< file.txt .数据流永远不会超过 80 个字符(它们可以是数字,也可以不是)。

我在程序中使用的函数是read() , strotol()strtok() ,“不相关”的代码流程如下:

  1. 使用 malloc分配 80 个初始字节的内存。
  2. 商店在 int , 通过 read()读取的字符数(我相信,最后一个 \0 )。
  3. realloc()重新分配内存为了节省尽可能多的内存(我知道在这种情况下它很简单,但是哦......)。

现在是棘手的一点:

  1. 由于数据必须用空格分隔,因此要检查的最大项目数最多为:(n/2)+1 , 其中n是在上点 nº 2 中读取的字符数。
  2. 创建 long 的数组最大尺寸是在第 1 点获得的数字。
  3. 填充numbers[0]结果为:strtol(strtok(line, delim), &end, 10) .
  4. 添加 1counter并输入 while循环:

    while((numbers[counter] = strtol(strtok(NULL, delim), &end, 10)) != NULL) {
    if(!*end) {
    // Check whether it's 0, 1, negative, prime or extract its factors
    }
    else {
    fprintf(stderr, "\"%s\" is not a non-negative integer", end)
    }
    counter++;
    }

现在,这里有一些输入和它们的输出:

输入:echo 1 2 3 4 5 6 7 8 9 10 | ./factors

输出:

1
2
3
2 2
5
2 3
7
2 2 2
3 3
2 5
Segmentation Fault (core dumped).

输入./factors < integers.txt其中 integers 包含一列整数。

输出:

所有的整数都被分解得很好,最后它打印出一个:

Segmentation Fault (core dumped). 

输入:echo abc 12 13 14 15 | ./factors

输出:

"abc" is not a non-negative integer
13
2 7
3 5
Segmentation Fault (core dumped).

输入:echo -1 -2 -3 -4 -5 | ./factors

输出:

"-1" is not a non-negative integer
"-2" is not a non-negative integer
"-3" is not a non-negative integer
"-4" is not a non-negative integer
"-5" is not a non-negative integer

输入:echo abc abc abc | ./factors

输出:

"abc" is not a non-negative integer

(并且不继续检查)。

输入:echo 3 4 0 6 7 | ./factors

输出:

3
2 2

(并且不继续检查)。

据我所知,它在遇到 0 时失败了, 一个以上的非 integer 实例或基本上在健康结束时 integer基于数据流。

知道我该如何解决这个问题,为什么它会如此明显地随机失败?

我应该让你知道我是 C 的新手......

非常感谢您。

============================================= =====

EDIT1:根据要求,这里是生成 numbers[] 的代码片段, 并从 stdin 中读取:

char *line;
char *end;
char *delim = " \n";
int charsread, counter;

line = malloc(80);
charsread = read(0, line, 81);
if (charsread == 0) {
return EX_OK;
}
realloc(line, charsread);
maxelem = (charsread / 2) + 1;
long numbers[maxelem];
numbers[0] = strtol(strtok(line, delim), &end, 10);
if (!*end) {
zeroone(numbers[0]);
}
else {
fprintf(stderr, "\"%s\" is not a non-negative integer\n", end);
}
counter = 1;
while [...]

最佳答案

尝试使用gdb调试segfault,通过设置合适的环境变量使其在segfaulting时dump一个core,或者直接在gdb中运行。段错误意味着您正在读/写不应该的内存部分。随机性意味着您可能正在粉碎堆栈或其他东西。我认为“printf”是罪魁祸首,请检查他们的论点。您也不检查数字是否小于数组长度?它可能会溢出吗?

关于c - 分解循环的结束条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937266/

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