我正试图释放所有的记忆,而且我不确定我是否正在为结构*做正确的事。我的代码片段:
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个月),我在开始时创建了一个struct指针数组。然后我用realloc动态增加数组的大小。当我从内存中释放aList时,它是否只释放存储在aList中的地址?
答案 0 :(得分:2)
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);
但这是将分配与免费匹配的问题。