Heap Error while deallocating memory

#include <iostream>

using namespace std;

int main()
{
unsigned char name[32] = "Rocky is my name";
unsigned char hptr[32];
memset(&hptr, 0, sizeof(hptr));
memcpy(hptr, name, 32);
cout << hptr;
free(hptr);
return 0;
}

Any help will be appreciated.
memset(hptr, 0, sizeof(hptr));

EDIT: Don't call free! You should call free/delete/delete[] only for memory you allocate with malloc/new/new[] respectively. hptr here is allocated on the stack, not on the heap. You don't have to (and you mustn't) free it.
Last edited on
Then how can I deallocate the memory used by hptr?
It is done automatically. You don't have to do anything.
Thanks Mate!!
It is done automatically. You don't have to do anything.

I believe that doesn't really answer the question correctly, it doens't have to be done automatically. If anyone might think it is deleted automaticly after it isn't used anymore, like after cout << hptr;, that isn't true. It get's deleted when the end of scope is reached, so in this case after
return 0;
is executed.
You can create you own scope, like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{
{
unsigned char name[32] = "Rocky is my name";
unsigned char hptr[32];
memset(&hptr, 0, sizeof(hptr));
memcpy(hptr, name, 32);
cout << hptr;
} //name and hptr are freed here, or at least, the destructor is called.
return 0;
}

if you want to free it before it the original scope was ended.
Last edited on
@ magnificence7 thank you Mate!!!
Topic archived. No new replies allowed.