【发布时间】:2016-02-29 18:13:37
【问题描述】:
我正在做一个项目,我不断收到分段错误,并且结构的值没有被传递。弄清楚为什么让我发疯。我试过用更简单的程序来解决问题,我想我已经找到了问题,但我不知道如何解决它。
问题是当我“malloc”一个结构时,然后按值传递,值就会丢失。稍后添加“免费”会产生分段错误。我不想从“malloc()”之前或“free()”之后访问一个值,所以我很困惑为什么会发生这种情况。
这是一个简单的问题模型:
#include <stdlib.h>
#include <stdio.h>
struct structexample
{
int element;
};
void initStruct(struct structexample * teststruct, int * number)
{
teststruct = malloc(sizeof(struct structexample));
teststruct->element = 10;
printf("teststruct element is %d in initStruct\n", teststruct->element);
*number = 5;
}
void printtest(struct structexample * teststruct, int * number)
{
printf("teststruct element is %d in printtest\n", teststruct->element);
printf("Number is %d\n", *number);
free(teststruct);
}
int main()
{
int number;
struct structexample teststruct;
initStruct(&teststruct, &number);
printtest(&teststruct, &number);
printf("teststruct element is %d in main()", teststruct.element);
return 0;
}
这会产生:
teststruct element is 10 in initStruct
teststruct element is -7967792 in printtest
Number is 5
Segmentation fault
我使用“gcc -Wall -pedantic -ansi”编译程序,没有出现任何错误或警告。
当我注释掉“malloc”和“free”时,它会正确生成:
teststruct element is 10 in initStruct
teststruct element is 10 in printtest
Number is 5
如果我只注释掉“free”但保留“malloc”,则可以修复分段错误,但结构的值仍然不正确。在这个简单的程序中,我真的不需要“malloc()”和“free()”,但在我的大型项目中确实需要它们。如果我能让它们在这个更简单的程序中工作,那么我想我可以修复更大的程序。很遗憾,我在 Google 上找不到类似的问题。
【问题讨论】:
-
Ansi C 已过时。使用 C99 或 C11。编译所有警告和调试信息(
gcc -Wall -Wextra -g可能还有-std=c99)。如果在 Linux 上,请了解 valgrind 并使用gdb(它有观察点)。