关于释放 C 语言内存的说明



我正在尝试释放我所有的内存,但我不确定我是否为结构*正确执行此操作。 我的代码片段:

struct words { char word[40]; };
int main() {
struct words* aList = malloc(2*sizeof(struct words));
// A text file is opened and each word is stored in a struct. I use an int variable to count how many times I've stored a word.//
if(n >= 2*sizeof(struct words) {
n = n*2;
aList = realloc(n*sizeof(struct words));
//Once my program is done, at the end of my main.//
free(aList);

根据我对 C 的理解(我只使用它大约 2 个月),我在开始时创建了一个结构指针数组。 然后,我使用 realloc 动态增加数组的大小。 当我从内存中释放 aList 时,它只释放存储在 aList 中的地址吗?

void* ptr = malloc(512);

这为您提供了一个包含 512 字节数据的内存块。这并不意味着块 512 字节大,而是意味着它包含 512 字节或更多。

通常,每个块都有一个由分配器使用的小前缀。

struct MemoryBlock {
    size_t howBigWasIt;
    char   data[0]; // no actual size, just gives us a way to find the position after the size.
};
void* alloc(size_t size) {
    MemoryPool* pool = getMemoryPool(size);
    MemoryBlock* block = getFirstPoolEntry(pool);
    block->howBigWasIt = size;
    return &block->data[0];
}
static MemoryBlock blockForMeasuringOffset;
void free(void* allocation) {
    MemoryBlock* block = (MemoryBlock*)((char*)allocation) - sizeof(MemoryBlock));
    MemoryPool* pool = getMemoryPool(block->howBigWasIt);
    pushBlockOntoPool(pool, block);
}

然后了解 realloc 是通过为新大小分配一个新块、复制数据并释放旧分配来实现的。

因此,您无法释放分配的子分配:

int* mem = malloc(4 * sizeof(int));
free(int + 3); // invalid

然而。

int i = 0;
int** mem = malloc(4 * sizeof(int*));
mem[0] = malloc(64);
mem[1] = alloca(22); // NOTE: alloca - this is on the stack.
mem[2] = malloc(32);
mem[3] = &i; // NOTE: pointer to a non-allocated variable.

您负责在此处免费()分配每个分配。

// mem[3] was NOT an malloc
free(mem[2]);
// mem[1] was NOT an malloc
free(mem[0]);
free(mem);

但这是一个将分配与免费匹配的问题。

最新更新