首页 文章

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

提问于
浏览
0

这个问题在这里已有答案:

我想在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");
    }
}

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

这是一个我已经遇到的编程问题,遗憾的是在某些情况下我无法使用像这样的char * allocate(char * arr,int size);并将返回值赋给char *数组 .

4 回答

  • 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但是应该没问题 .

  • 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;
    }
    
  • 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 仍然是(指针)的副本,但它指向 y . 对该功能外的 x 的更改不会显示 . 但改变 *x 会修改 y .

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

    int allocate(char** arr, int size) {
        *arr = malloc(size);
    }
    
    char *ptr;
    allocate(&ptr);
    
  • 0

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

    char *array = NULL;

相关问题