c - 将指针内存分配从 main() 移动到函数并在其他函数中使用指针

标签 c pointers memory

嘿,我正在尝试将指针内存分配 d =(deque*)malloc(sizeof(deque)); 移动到名为 void initDeque() 的第一个函数中。我尝试在 main 中保留声明并在函数中分配内存,但程序在初始化双端队列后崩溃,我无法在其他函数中使用指针。

代码如下:

int main(){
    int x;
    deque *d;
    d = (deque*)malloc(sizeof(deque));

    initDeque(d);
    putFront(d,10);

以及我想为指针移动内存分配的函数:

void initDeque(deque *d){ //Create new deque
    //d = (deque*)malloc(sizeof(deque));
    printf("Initializing deque\n");
    d->front=NULL;
    d->rear=NULL;
}

如果声明和分配在 main() 中,程序运行良好,但当我将分配放入 void initDeque 时程序崩溃。

最佳答案

参数(甚至指针)是 passed by value在 C 中。

所以返回指针:

deque *make_queue(){ //Create new deque
  deque *d = malloc(sizeof(deque));
  if (!d) { perror("malloc"); exit(EXIT_FAILURE); };
  printf("Initializing deque\n");
  d->front=NULL;
  d->rear=NULL;
  return d;
}

并在 main 的开头调用 d = make_queue();;在执行 malloc总是测试失败

或者,传递一个指针的地址,如answered by clcto

C dynamic memory management 上阅读维基页面.不要忘记适本地调用 free。对于调试,使用 valgrind如果可供使用的话。避免 memory leaks (和双 free-s)。当您在 C 方面更加成熟时,请阅读 garbage collection 上的维基页面。 , 也许考虑在某些情况下使用 Boehm conservative garbage collector .

关于c - 将指针内存分配从 main() 移动到函数并在其他函数中使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29105267/

相关文章:

c - 这段代码发生了什么

c++ - 如何使用指针来引用数组中元素的地址?

c++ - 为什么释放内存会导致崩溃?

memory - 了解 F# 内存消耗

c++ - 访问无效指针并获取其地址

c - Microchip C18 - 奇怪的代码行为(可能与扩展模式/非扩展模式相关)

c - strtoull 和 long long 算术

c - autoconf 仅在必要时设置 -fPIC

c - 未初始化的指针与 NULL 和 0

c - 这个 int 指针示例需要 malloc 吗?