Operating System - HP-UX
1829547 Members
2383 Online
109992 Solutions
New Discussion

Strange behavior of new-delete/malloc-free

 
SOLVED
Go to solution
Shashibhushan Gokhale
Occasional Contributor

Strange behavior of new-delete/malloc-free

Hi All,

Please go through the attached code:

Here
1. I allocate space to a unsigned int ** variable using new and also malloc later.
2. I assign some value to it.
3. I print the value.
4. I ***DEALLOCATE*** the allocated space using delete/free.
5. I ***ASSIGN*** values to deallocated pointer.
6. I print the values using the pointer(***DEALLOCATED***).


I know that the memory is freed(returned back to the system) after a call to delete/free.

In this example I am not only referencing data at locations already deallocated but am also reassigning some values at the locations.

This code snippet works perfectly fine, without even a warning when I was expecting segmentation violation/Bus Error core-dump.

Can anyone please explain this strange behavior.

Regards,
Shashibhushan Gokhale
2 REPLIES 2
Steven Gillard_2
Honored Contributor

Re: Strange behavior of new-delete/malloc-free

This is actually normal behaviour. You'll only get a SIGSEGV if you try to access a memory address outside your processes address space.

The malloc/free/new/delete operators are all implemented with the underlying brk/sbrk system calls. When you call the malloc or new library routine, your data segment will be expanded through a call to sbrk(). When you call free or delete, the data segment is NOT reduced. The memory region is just added to a free list by the delete/free routine so your process can allocate it again later.

Therefore according to the OS, the addresses your process is trying to access are all valid because they are still within your processes data segment, so the signals are not delivered. Set the pointer to NULL or some other random value after freeing it and you'll get your core.

This is where a tool like Purify really helps out. Grab an evaluation copy and watch it scream at your program.

Regards,
Steve
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Strange behavior of new-delete/malloc-free

As mentioned, this is perfectly normal because the memory is still mapped to the processes Virtual Address Space. You are actually operating under a misconception. Free() does not return memory the to system; it merely allows subsequent malloc()'s within the same process to reuse the memory. The only way to return memory to the OS is through the sbrk() system call; however, if you use sbrk() you must not use malloc(), calloc(), ... free() or absolute chaos is assured.
If it ain't broke, I can fix that.