首页 > 解决方案 > 带有 malloc 的指针无法在函数中存活

问题描述

我是一个 C 初学者,我不明白为什么我在这里遇到错误。我被告知指针可以在带有 的函数中存活malloc,但在这里我得到了code dumped.

我需要得到这个并且在互联网上找不到任何东西。我知道你可以做到完全不同,但我不想使用全局变量或指向指针的指针。我很想了解malloc

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

void doStuff();

void doStuff(int *a) {
    a = malloc(sizeof(int));
    *a = 3;
    printf("%d \n", *a);
};

int main() {
    int *a;

    doStuff(a);
    printf("%d", *a);

    free(a);
}

标签: cmalloc

解决方案


你掉进了经典的 c 函数参数陷阱。阅读本文以了解 c 中的“按值传递”。阅读并理解该链接中的所有内容非常重要,但简单的版本是您分配给的值a不会在函数之外存在。重要的是要注意在这里使用 malloc 是无关紧要的,这是你传递导致问题的参数的方式。

您在评论中包含的参考资料显示了您将如何在 malloc 部分中正确执行此操作:

#include <stdlib.h>

/* allocate and return a new integer array with n elements */
/* calls abort() if there isn't enough space */
int *
makeIntArray(int n)
{
     int *a;

     a = malloc(sizeof(int) * n);

     if(a == 0) abort();                 /* die on failure */

     return a;
}

但是,如果您不需要使用malloc,则创建一个 int,传递 int 的地址,然后直接在函数中更改它,如下所示:

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

void doStuff();

void doStuff(int *a){
    *a = 3;
    printf("%d \n", *a);
};

int main(){
    int a;

    doStuff(&a);
    printf("%d", a);
}

推荐阅读