且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我尝试使用 struct 运行程序时出现分段错误(核心转储)

更新时间:2022-02-04 00:55:06

我不太明白您要实现的所有目标,但这里有一些问题.

I don't quite understand all of what you are trying to achieve, but here are a few issues.

  1. 您可能不需要日月年变量.
  2. 这一行

  1. You probably don't need the day month year variables.
  2. This line

day = atoi(oken);

应该是

res2[i].day = atoi(oken);

读取size

fscanf(file, "%d", &size)

这读取一个整数但它不读取尾随的换行符

你需要把它改成这样

fscanf(file, "%d\n", &size)

或使用 fgets.

由于尾​​随换行符,下次调用 gets 时,您将获得一个仅包含换行符的字符串.

Because of the trailing newline, the next time you call gets you obtain a string containing just the newline.

您的 strtok 调用和 NULL 检查不同步.第一个,对于 oken 是可以的.但是然后你做了一个 strtok 返回 coken 但对 oken 的空检查,最后一个 strtok 返回 yoken 和对 coken 的 NULL 检查.在所有 3 种情况下,对 strtok 的调用之后应该对返回值进行 NULL 检查(与 oken 的情况一样).

Your strtok calls and NULL checks are out of phase. The first one, for oken is OK. But then you do a strtok returning coken but a NULL check on oken and lastly a strtok returning yoken and a NULL check on coken. In all 3 cases, the call to strtok should be followed by a NULL check on the returned value (as is the case for oken).

我不明白 while (l 循环的目的(可能是因为上面描述的换行符处理不当?).您分配 5 个结构,从 structs.txt 中读取 4 个到 res2(元素 0 到 3)然后将 res2 的元素 1 到 4 复制到 res.这意味着 res2 的元素 0 不会被复制,元素 4 是全零会被复制.

I don't understand the purpose of the while (l < size) loop (maybe because of the mishandling of the newline as described above?). You allocate 5 structs, read 4 from structs.txt into res2 (elements 0 to 3) then you copy elements 1 to 4 of res2 into elements 0 to 3 of res. This means that element 0 of res2 doesn't get copied and element 4 which is all zeroes does get copied.

崩溃的原因是第 3 点和第 4 点的组合.

The cause of the crash is a combination of points 3 and 4.

我建议不要使用 atoi,因为它不进行错误检查.除非您确定字符串包含格式正确的整数,否则使用它是不安全的.如果你想让你的代码健壮,你需要添加更多的错误检查,例如,检查 malloccalloc 的返回值.

I would advise against using atoi as it does no error checking. It is unsafe to use unless you are certain that the string contains a well-formed integer. If you want your code to be robust, you need to add more error checking e.g., check the return values of malloc and calloc.