gpt4 book ai didi

c - 在函数中释放 malloc 结构

转载 作者:太空狗 更新时间:2023-10-29 15:11:14 24 4
gpt4 key购买 nike

我正在创建一个包含缓冲区功能的源文件,我想将其用于我正在创建的其他库。

它工作正常,但我无法摆脱我在其中一个函数中创建的缓冲区结构。以下片段应该有助于说明我的问题:

C 头文件:

//dbuffer.h
...

typedef struct{
char *pStorage;
int *pPosition;
int next_position;
int number_of_strings;
int total_size;
}DBUFF;
...

C 源代码:

//dbuffer.c
...
DBUFF* dbuffer_init(char *init_pArray)
{
//Find out how many elements the array contains
int size = sizeof_pArray(init_pArray);

//Initialize buffer structure
DBUFF *buffer = malloc(sizeof(DBUFF));

//Initialize the storage
buffer->pStorage = malloc( (sizeof(char)) * (size) );

strncpy( &(buffer->pStorage)[0] , &init_pArray[0] , size);
buffer->number_of_strings = 1;

buffer->total_size = size;
buffer->next_position = size; //size is the next position because array allocates elements from 0 to (size-1)

//Initialize the position tracker which keeps record of starting position for each string
buffer->pPosition = malloc(sizeof(int) * buffer->number_of_strings );
*(buffer->pPosition + (buffer->number_of_strings -1) ) = 0;

return buffer;
}

void dbuffer_destroy(DBUFF *buffer)
{
free(buffer->pStorage);
free(buffer);
}
...

主要:

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


int main(int argc, char** argv)
{
DBUFF *buff;

buff = dbuffer_init("Bring the action");
dbuffer_add(buff, "Bring the apostles");
printf("BUFFER CONTENTS: ");
dbuffer_print(buff);

dbuffer_destroy(buff);

// Looks like it has been succesfully freed because output is garbage
printf("%s\n", buff->pStorage);

//Why am I still able to access struct contents after the pointer has been freed ?
printf("buff total size: %d\n", buff->total_size);

return (EXIT_SUCCESS);
}

输出:

BUFFER CONTENTS: Bring the action/0Bring the apostles/0
��/�
buff total size: 36

RUN SUCCESSFUL (total time: 94ms)

问题:

为什么在释放指向结构的指针后我仍然可以使用下面的行访问结构内容?

printf("buff total size: %d\n", buff->total_size);

最佳答案

在分配的指针上调用free() 后,尝试使用指针调用undefined behavior .你不应该那样做。

引用 C11 标准,章节 §7.22.3.4,free() 函数

The free() function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. [..]

它从来没有提到您可能(错误地)期待的清理

为了清楚起见,调用 free() 并不总是真正释放分配的物理内存。它只是使该指针(内存空间)能够再次分配(例如,返回相同的指针)以用于连续调用 malloc() 和 family。在调用 free() 之后,您的程序中不应再使用该指针,但是 C 标准不保证 cleanup分配内存。

关于c - 在函数中释放 malloc 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32884431/

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