Home > Blockchain >  If I have heap allocated member in my struct, do I have to allocate the struct itself in the heap?
If I have heap allocated member in my struct, do I have to allocate the struct itself in the heap?

Time:10-24

struct Vector {
    size_t size;
    char ** data;
} Vector;

I have a vector struct. Do I have to allocate the Vector on heap if the struct has dynamically allocated data?

CodePudding user response:

No, there is no such rule. A pointer residing in any part of memory may point to any other part of memory.

That said, if your struct Vector is allocated in a different way than its data, then the two might end up with different lifetimes, and it might be harder to avoid use-after-free bugs or memory leaks. So if data is dynamically allocated, most of the time you will want struct Vector to be dynamically allocated too. But it's not a requirement.

  • Related