William McCarty
William McCarty

Reputation: 839

Deleting memory from function C++

I'm having trouble freeing my memory I'm using and a little confused how I would go about doing it. When I do it with the code below i get an error "Heap Corruption Detected... CRT detected that the application wrote to memory after end of heap buffer". I also debugged to make sure there is a memory leak using the Crtdb and there is a leak on that variable. Just am confused how to free it.

#include <iostream>
#include <string.h>

using namespace std;
void adjustVar(char*& pointer, size_t i) {
   pointer = new char[i];
}

int main(void) {
   const char* org = "HELLOWORLD";
   char* p = nullptr;
   size_t size = strlen(org);
   adjustVar(p, size);
   memset(p, 0, size+1);
   strncpy(p, org, size);
   cout << p << endl;
   delete[] p;
   return 0;
}

Upvotes: 2

Views: 113

Answers (2)

M.M
M.M

Reputation: 141574

In the updated code, you actually do overflow the buffer, causing heap corruption:

size_t size = strlen(org);
adjustVar(p, size);
memset(p, 0, size+1);    // overflow by 1 byte

Also, It is poor style to use memset and strncpy like that; replace with:

size_t size = strlen(org);
adjustVar(p, size + 1);
strcpy(p, org);

strncpy has very few valid uses, because it does not terminate its buffer in some cases; either strcpy or memcpy should be preferred, depending on what you want.

Upvotes: 3

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

It runs fine here: http://ideone.com/Ap2DjG

As an answer though, don't use pointers. If you find yourself using char* use std::string instead. And if you absolutely have to use pointers then consider wrapping them in boost or c++11 smart pointers.

Upvotes: 1

Related Questions