gpt4 book ai didi

c - 如何释放在双指针结构上分配的内存

转载 作者:行者123 更新时间:2023-12-02 18:44:50 25 4
gpt4 key购买 nike

如何释放在此结构中分配的内存

struct image_t {
char type[3];
int **ptr;
int width;
int height;
};

在第一个函数中,我进行了这些分配:

    struct image_t *struktura = (struct image_t *)malloc(sizeof(struct image_t));
int **ptr = (int**)malloc(struktura->height * sizeof(int*));

for (i = 0; i < struktura->height; i++) {
*(ptr + i) = (int *)malloc(struktura->width * sizeof(int));
if (*(ptr + i) == NULL) {
break;
}
}

在第二个函数中,我必须释放分配的内存,因此我尝试释放类似这样的内存,但它不起作用

void destroy_image(struct image_t **m) {
if (m != NULL) {
if (*m != NULL) {
if ((*m)->ptr != NULL) {
for (int i = 0; i < (*m)->height; i++) {
free(*((*m)->ptr + i));
}
free((*m)->ptr);
free(*m);
}
}
}
}

我无法更改销毁函数的声明,因此结构上必须有双指针。

最佳答案

为了使您的销毁函数正常工作,指针数组中的所有指针必须有效或为空。 malloc() 返回的内存未初始化,因此在分配函数中跳出循环会使指针数组的其余部分未初始化,因此不应传递给 free() .

另请注意,您应该测试结构指针和指针数组的分配失败。此外,新分配的结构的 widthheight 成员未初始化:您应该使用函数参数来初始化它们。

destroy_image 函数应该在释放后将 *m 设置为 NULL 并且必须 free(*m); 即使 (*m)->ptr 是空指针。

以下是此问题的解决方案:

  • 使用calloc()分配数组(在所有情况下都是一个好主意)或
  • height设置为成功分配的指针的数量。
  • 显式将数组中的剩余指针设置为NULL
  • 分配失败时释放已分配的 block 并返回NULL

这是修改后的版本:

#include <stdlib.h>

struct image_t {
char type[3];
int **ptr;
int width;
int height;
};

struct image_t *allocate_image(int width, int height) {
struct image_t *struktura = calloc(1, sizeof(*struktura));

if (struktura == NULL)
return NULL;

// should initialize struktura->type too
struktura->width = width;
struktura->height = height
struktura->ptr = calloc(height, sizeof(*struktura->ptr));
if (struktura->ptr == NULL) {
free(struktura);
return NULL;
}

for (int i = 0; i < height; i++) {
struktura->ptr[i] = calloc(sizeof(*struktura->ptr[i]), width);
if (struktura->ptr[i] == NULL) {
// Iterate downwards on index values of allocated rows
// (i --> 0) is parsed as (i-- > 0)
// this test works on signed and unsigned index types, unlike (--i >= 0)
while (i --> 0) {
free(struktura->ptr[i]);
}
free(struktura->ptr);
free(struktura);
return NULL;
}
}
return struktura;
}

void destroy_image(struct image_t **m) {
if (m != NULL) {
struct image_t *p = *m;

if (p != NULL) {
if (p->ptr != NULL) {
for (int i = 0; i < p->height; i++) {
free(p->ptr[i]);
}
free(p->ptr);
}
free(p);
*m = NULL;
}
}
}

关于c - 如何释放在双指针结构上分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67580911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com