繁体   English   中英

澄清C语言中的释放内存

[英]Clarification on freeing memory in 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.

您有责任在这里free()分配每个分配。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM