带有malloc的指针无法保留功能

问题描述 投票:1回答:3

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

我需要获取它,并且在Internet上找不到任何内容。我知道您可以做的完全不同,但是我不想使用全局变量或指向指针的指针。我很想学习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);
}
c malloc
3个回答
1
投票

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

您在注释中包含的reference在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);
}

0
投票

这里有两个a。两个都是指针。一个属于main(),另一个属于dostuff()。当您从main()传递a时,未初始化的值传递到dostuff的a。上,当您malloc dostuff传递一个新地址并在新地址处更新值时,然而main()的值仍未初始化。解决问题的方法是在main函数中执行malloc。或者从dostuff返回a并在main()中对其进行更新。

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

int *doStuff();

int *doStuff(int *a){

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


int main(){
    int* a;

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

    free(a);
}

0
投票

a中的doStuff()变量是该函数的局部变量,它的参数是与a中的main()不同的对象。在a中传递main()变量的值具有未定义的行为,因为amain()中未初始化。

要获得正确的行为,请将doStuff()更改为不带参数并返回int*

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

int *doStuff(void);

int *doStuff(void) {
    int *a = malloc(sizeof(int));
    if (a != NULL) {
        *a = 3;
        printf("in doStuff: %d\n", *a);
    }
    return a;
}

int main() {
    int *a;

    a = doStuff();
    if (a != NULL) {
        printf("in main: %d\n", *a);
        free(a);
    } else {
        printf("doStuff returned a NULL pointer\n");
    }
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.