简体   繁体   中英

posix_memalign memory allocation and memory free

In the following codes, do I need to free allocated_memory2 and allocated_memory3? Do you think this code is free of memory leaks?

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);
}

You are allocating a single block of memory. The other two pointers simply point into that memory. Therefore, you don't have a memory leak, but you do have invalid free s which means undefined behavior (likely crashing the program or worse).

Also, you should check the return value of posix_memalign for errors.

Ideally, you would use a std::unique_ptr to keep track of the allocated memory, which means you won't need to write a destructor. Use a custom deleter to ensure it is released with free .

Finally, it is best if you explicitly disable copy/move for this class unless you handle it.

Free'ing only allocated_memory1 (allocated by posix_memalign call) is sufficient/correct. allocated_memory2 and allocated_memory3 are simply pointers to different parts of the same block of memory. So free'ing them is incorrect.

You may avoid exposing the allocated_memory1 pointer directly - in case it get changed, you might not be able to free it. You could use:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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