退出函数时为什么动态分配函数参数的内存会丢失?

时间:2014-12-13 08:15:44

标签: c memory pass-by-value

我想在C中创建一个函数,它将为函数参数中的指针动态分配内存。

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

int allocate(char * arr, int size){
    int code = -1;
    arr = malloc(size);
    if(arr != NULL) code = size;

    return code;    
}

void main(){
    char * array;

    if(allocate(array,4) != -1){
        printf("allocated!\n");

        if(array == NULL) printf("Oops it actually didn't allocate!\n");
    }
} 

当我执行程序时;它只会显示&#34;已分配!&#34;并且&#34;哎呀它实际上没有分配!&#34;。这意味着内存分配确实发生了(因为函数的返回码不是-1。但是当我检查数组是否等于NULL时;它实际上是!

这是我遇到的编程问题,遗憾的是在某些情况下我无法使用像char * allocate(char * arr,int size)这样的解决方法;并将返回值赋给char * array。

4 个答案:

答案 0 :(得分:7)

你缺乏间接水平,你需要char **。

原谅格式错误,我是用手机写的。

Char *数组,数组绑定到一个内存槽(它将包含一个指向另一个将被解释为char的内存槽的值)。

因此,您将该值复制到该函数并在allocate中本地修改该值,但修改永远不会到达外部范围。

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

int allocate(char ** arr, int size){
    int code = -1;
    *arr = malloc(size);
    if(*arr != NULL) code = size;

    return code;    
}

void main(){
    char * array;

    if(allocate(&array,4) != -1){
        printf("allocated!\n");

        if(array == NULL) printf("Oops it actually didn't allocate!\n");
    }
} 

在10年内没有完成C,但应该没问题。

答案 1 :(得分:2)

您可以在函数内部分配内存并返回地址,如下所示 还有一些更改,而不是void main应该是int main()

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

char *allocate( int size){
    char *arr;
    arr = malloc(size);

    return arr;    
}

int main(){
    char * array;

    if((array = allocate(4)) != NULL){
        printf("allocated!\n");
    }
    return 0;
} 

答案 2 :(得分:1)

C中函数的参数按值传递。这意味着以下功能毫无意义:

void f(int x) {
    x = 1;
}

int y = 0;
f(y);
// y is still 0

调用f时,y会复制到x。对x所做的任何更改都会更改,但不会影响y。要解决此问题,您需要使用返回值或将指针传递给y

void f(int* x) {
    *x = 1;
}

int y = 0;
f(&y);
// y is now 1

此处x仍然是(指针)的副本,但它指向yx的更改在该函数之外不可见。但更改*x会修改y

相同的规则适用于指针参数。对于要修改的参数,您只需要一个*

int allocate(char** arr, int size) {
    *arr = malloc(size);
}

char *ptr;
allocate(&ptr);

答案 3 :(得分:0)

另请注意,在此处检查array NULL是不够的,因为本地定义的变量可能包含垃圾值(因此,不是NULL)。您必须在分配

之前为其分配NULL

char *array = NULL;

相关问题