gpt4 book ai didi

C 代码在 Eclipse-Kepler 中运行,但在 Codeblocks IDE 中运行失败

转载 作者:行者123 更新时间:2023-11-30 17:44:23 25 4
gpt4 key购买 nike

我是 C 编程新手,也是 Stackoverflow 的新手。

我有一些在 Eclipse Kepler (Java EE IDE) 中编译和运行的 C 代码;我安装了 C/C++ 插件和 Cygwin Gcc 编译器。在 Eclipse IDE 中一切运行正常;然而,当我的 friend 尝试在他的 Codeblocks IDE 上运行相同的代码时,他没有得到任何输出。在某个时候,他遇到了一些段错误,我们后来了解到这是由于我们的程序访问了不属于我们程序的内存空间。

Codeblocks IDE 使用 Gcc 编译器而不是 cygwin gcc,但我不认为它们有什么不同会导致此类问题。

我知道 C 语言非常原始且不标准化,但为什么我的代码可以在 eclipse 中使用 cygwin-gcc 编译器运行,但不能在 Codeblocks IDE 中使用 gcc 编译器运行?

请帮忙,这对我们的类(class)项目很重要。

谢谢大家。

[编辑]我们的代码有点大,无法粘贴到这里,但这里有一个示例代码,它在 Eclipse 中运行成功,但在代码块中失败,如果您有代码块,请自行尝试:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>


int main(void) {
char *traceEntry1;
FILE *ifp;

traceEntry1 = malloc(200*sizeof(char));
ifp = fopen("./program.txt", "r");

while (fgets(traceEntry1, 75, ifp))
printf("String input is %s \n", traceEntry1);
fclose(ifp);
}

它根本不会在代码块中提供任何输出,有时只会导致段错误。

我不知道问题是什么。

我们需要您的帮助,提前致谢。

最佳答案

始终测试所有(相关)调用的结果。 “相关”至少是那些在调用失败时返回不可用结果的调用。

就OP的代码而言,它们是:

  • malloc()
  • fopen()
  • fclose()

OP 代码的保存版本可能如下所示:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int result = EXIT_SUCCESS; /* Be optimistic. */
char * traceEntry1 = NULL; /* Always initialise your variables, you might remove this during the optimisation phase later (if ever) */
FILE * ifp = NULL; /* Always initialise your variables, you might remove this during the optimisation phase later (if ever) */

traceEntry1 = malloc(200 * sizeof(*traceEntry1)); /* sizeof(char) is always 1.
Using the dereferenced target (traceEntry1) on the other hand makes this
line of code robust against modifications of the target's type declaration. */
if (NULL == traceEntry1)
{
perror("malloc() failed"); /* Log error. Never ignore useful and even free informaton. */
result = EXIT_FAILURE; /* Flag error and ... */
goto lblExit; /* ... leave via the one and only exit point. */
}

ifp = fopen("./program.txt", "r");
if (NULL == ifp)
{
perror("fopen() failed"); /* Log error. Never ignore useful and even free informaton. */
result = EXIT_FAILURE; /* Flag error ... */
goto lblExit; /* ... and leave via the one and only exit point. */
}

while (fgets(traceEntry1, 75, ifp)) /* Why 75? Why not 200 * sizeof(*traceEntry1)
as that's what was allocated to traceEntr1? */
{
printf("String input is %s \n", traceEntry1);
}

if (EOF == fclose(ifp))
{
perror("fclose() failed");
/* Be tolerant as no poisened results are returned. So do not flag error. It's logged however. */
}

lblExit: /* Only have one exit point. So there is no need to code the clean-up twice. */

free(traceEntry1); /* Always clean up, free what you allocated. */

return result; /* Return the outcome of this exercise. */
}

关于C 代码在 Eclipse-Kepler 中运行,但在 Codeblocks IDE 中运行失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20022816/

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