c - Malloc() 和 free() 阻止我在 C 中按值传递结构

标签 c ansi-c

我正在开发一个项目,并且不断出现段错误,并且结构的值没有被传递。弄清楚为什么让我发疯。我尝试用更简单的程序来解决问题,我想我已经找到了问题,但我不确定如何解决它。

问题是,当我“malloc”一个结构,然后按值传递时,该值会丢失。稍后添加“free”会产生段错误。我没有尝试访问“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 上找不到类似的问题。

最佳答案

您正在混合堆栈和堆

void initStruct(struct structexample * teststruct, int * number)
 {
     teststruct = malloc(sizeof(struct structexample)); 
     ^ There is no need to use malloc, teststruct is on the stack

 ...

int main()
{
    int number;
    struct structexample teststruct;
    initStruct(&teststruct, &number);

关于c - Malloc() 和 free() 阻止我在 C 中按值传递结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35706559/

相关文章:

C 数组 malloc() VS {}

c - 在 C 中以原子方式比较两个整数的最快方法?

c - 在C中读入并记录一个数字

c - 如何从非浏览器设备发出 HTTP POST?

c - 枚举常量的翻译限制

c - 错误 : initializer element is not computable at load time

c - 2 个 printf() 之间的程序段错误

从 C 中的字符串计算奇偶校验位

c - 另一个 "Why is my Uva 3n+1 solution not being accepted?"问题

c - 如何从C程序向Linux命令发送命令