相关疑难解决方法(0)

在Linux下释放C中的内存

如果你没有释放你在Linux下的C程序中使用malloc的内存,它什么时候发布?程序终止后?或者内存是否仍然被锁定,直到一个不可预见的时间(可能在重新启动时)?

c linux memory-management

1
推荐指数
2
解决办法
2019
查看次数

为什么我要 free() 一个由 malloc() 分配的对象?

我总是被告知释放由malloc()以下分配的堆内存:

#include <stdlib.h>

#define width 5

int main(void)
{
    char* ptr = malloc(sizeof(*ptr) * width);

    /* some stuff with the heap object */

    free(ptr);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是现在我已经阅读了当您在 malloc 之后不释放时真正会发生什么?我不必这样做,因为操作系统会在程序终止后自动释放占用的内存。

但是当时为什么我的老师要我这样做呢?这样做有什么好处吗?

c malloc free memory-management heap-memory

0
推荐指数
1
解决办法
131
查看次数

分配二维结构数组

我想分配一个自定义类型“cell”的二维数组,它是一个结构。但是,我做错了,请参阅下面的代码。你能告诉我我的错误在哪里吗?

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

typedef struct
{
  int variable_1;
  int variable_2;
  int variable_3;
} cell;


void initialiseArray(unsigned long rows, unsigned long columns, cell array[rows][columns])
{
  for (int i = 0; i < rows; i = i + 1)
    for (int j = 0; j < columns; j = j + 1)
    {
      array[i][j].variable_1 = 0;
      array[i][j].variable_2 = 0;
      array[i][j].variable_3 = 0;
    }
}

int main()
{
  unsigned long rows = 200;
  unsigned long columns = 250;
  cell* array[rows];
  for …
Run Code Online (Sandbox Code Playgroud)

c struct multidimensional-array

0
推荐指数
1
解决办法
71
查看次数

如果在函数返回之前忘记释放内存,如何释放函数外的内存

我的问题可以简要显示为以下示例。

void func(int n){

    char *p = (char*)malloc(n);

    // some codes

    memset(p,0,sizeof(name));

    // free(p); // Commenting this line represents that I forget to release the allocated memory.
}


int main(){

    // some codes

    for (int i; i < Nl; i++){

        func(100);

        // How can I release the allocated memory of p outside of the func?
    }

}
Run Code Online (Sandbox Code Playgroud)

我希望释放已分配的内存,该内存是在该函数之外的函数中分配的。

谢谢你。

c c++ memory-leaks

-1
推荐指数
1
解决办法
124
查看次数