gpt4 book ai didi

c++ - posix_memalign 内存分配和内存释放

转载 作者:行者123 更新时间:2023-11-30 03:14:41 25 4
gpt4 key购买 nike

在下面的代码中,是否需要释放allocated_memory2和allocated_memory3?你认为这段代码没有内存泄漏吗?

class data {
public:
data();
~data();
unsigned char *allocated_memory1;
unsigned char *allocated_memory2;
unsigned char *allocated_memory3;
};

data::data() {
posix_memalign((void **) &allocated_memory1, 16, 1040);
memset(allocated_memory1, 0, 1040);

allocated_memory2 = allocated_memory1 + 4;
allocated_memory3 = allocated_memory1 + 16;
}

data::~data() {
free(allocated_memory3);
free(allocated_memory2);
free(allocated_memory1);
}

最佳答案

仅释放 allocated_memory1(由 posix_memalign 调用分配)就足够/正确了。 allocated_memory2allocated_memory3 只是指向同一内存块不同部分的指针。所以释放它们是不正确的。

您可以避免直接公开 allocated_memory1 指针 - 万一它被更改,您可能无法释放它。你可以使用:

class data {

private:
unsigned char *allocated_block;

public:
data();
~data();
unsigned char *allocated_memory1;
unsigned char *allocated_memory2;
unsigned char *allocated_memory3;
};

data::data() {
posix_memalign((void **) &allocated_block, 16, 1040);
memset(allocated_block, 0, 1040);

allocated_memory1 = allocated_block + 4;
allocated_memory2 = allocated_block + 4;
allocated_memory3 = allocated_block + 16;
}

data::~data() {
free(allocated_block);
}

关于c++ - posix_memalign 内存分配和内存释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637877/

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