C++ how to delete a structure?

Rella picture Rella · Nov 9, 2010 · Viewed 71.1k times · Source

Structure I created:

   struct VideoSample
  { 
      const unsigned char * buffer;
      int len;
  };

   VideoSample * newVideoSample = new VideoSample;
   newVideoSample->buffer = buf;
   newVideoSample->len = size;

       //...

How now to delete it now?

Answer

Amarghosh picture Amarghosh · Nov 9, 2010
delete newVideSample;

This won't free any memory you allocated to newVideoSample->buffer though - you have to free it explicitly before deleting.

//Free newVideSample->buffer if it was allocated using malloc
free((void*)(newVideSample->buffer));

//if it was created with new, use `delete` to free it
delete newVideSample->buffer;

//Now you can safely delete without leaking any memory
delete newVideSample;

Normally this kind of freeing is written in the destructor of the class so that it'll be called automatically when you delete the dynamically created object.

Thanks @steve for mentioning it :)