我试图释放我所有的记忆,我不确定我是否在一个struct*上做得正确。我的代码片段:
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);
但这是一个分配与释放匹配的问题。