我是C编程的新手,也是Stackoverflow的新手。
我有一些c代码可以在Eclipse Kepler(Java EE IDE)中编译和运行;我为c安装了C / C ++插件和Cygwin Gcc编译器。 在Eclipse IDE中一切运行正常;但是,当我的朋友试图在他的Codeblocks IDE上运行相同的代码时,他没有得到任何输出。在某些时候,他得到了一些分段错误,我们后来得知这是因为我们的程序访问了不属于我们程序的内存空间。
Codeblocks IDE正在使用Gcc编译器而不是cygwin gcc,但我不认为它们会导致这类问题。
我知道C非常原始且非标准化,但为什么我的代码会在使用cygwin-gcc编译器的eclipse中运行,而不能在使用gcc编译器的Codeblocks IDE中运行?
请帮助,这对我们的课程项目非常重要。
感谢所有人。
[编辑]我们的代码有点大,可以在这里粘贴,但是这里有一个示例代码,它可以在eclipse中运行RUN SUCCESSFULLY但在代码块中使用FAIL,如果你有代码块请自己尝试一下:
#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);
}
它根本不会在代码块中提供任何输出,有时只会导致分段错误。
我不知道问题是什么。
我们需要你的帮助,谢谢你。
答案 0 :(得分:0)
始终并且一直在测试所有(重要)电话的结果。 “相关”至少是那些在呼叫失败时返回无法使用的结果的电话。
对于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. */
}