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?
The best way to explicitly remove a Struct is to assign an empty value to the struct variable that refers to a Struct. Example: Assign a new value to the Struct variable that refers to the Struct.
delete keyword in C++ Which means Delete operator deallocates memory from heap. Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.
Overall, the combination allows deleting the array of structs using delete[] .
if a struct is created as a variable in a scope, it is automatically deleted at the end the the scope. And if you are creating it with "new", why don't you use "delete" to free it ?
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 :)
delete newVideoSample;
But if the new
and delete
are in the same context, you're probably better off skipping them and just creating it on the stack instead:
VideoSample newVideoSample = {buf, size};
In that case, no cleanup is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With