Memory Deallocation

Memory Deallocation

I have a byte pointer pointing to a message buffer. I want to know how can I delete just the first two bytes of this message and pass on the rest of the message to the application.

If I simply pass on a shifted pointer pointing to the third byte, the application gets an error, when deleting the shifted message pointer, which says that there is a memory leak (which must be the first two bytes).

My trouble is that I am also not allowed to copy the message from third bytes on to another buffer. How should I get rid of first two bytes ?

You have two options: either avoid dynamic allocation altogether and use stack or static memory instead, or?in case you must use dynamic memory?make sure that the function that deletes the buffer decrements the pointer by two bytes before actually deleting it. For example:

void reader(char * pmessage){ //.. process message buffer char *p = pmessage -2; delete [] p; // now fine}
See also  Comparing different methods of testing your Infrastructure-as-Code

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist