Question

I want to make a memory allocation of a struct like the following in C++. Is it fine to do it like:

m_temppkt = new pktstruct();

and the struct is:

 struct pktstruct {
   void *address;
   int length;
   struct pktstruct *next;
 };
Was it helpful?

Solution

It is fine to do that, but the memory in m_temmkt->address will not be allocated (i.e. you allocate space for the pointer, not for the memory the pointer will point to).

The best solution is to initialize the values using a constructor:

struct pktstruct {
    void *address;
    int length;
    struct pktstruct *next;
    pktstruct(void* s, int l);
};

pktstruct::pktstruct(void* a, int l)
: address(a), length(l), next(NULL)
{
}

m_temppkt = new pktstruct(NULL, 0); // initializes with { NULL, 0, NULL }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top