Question

Hi I am learning some debugging concepts. In this program i am trying to simulate core dump. I expect core will be dumped But it's not generate core. Program execute without any issue.

First i allocate 20 bytes for ptr. I copy one new string to ptr. Then i free ptr then print ptr it working without any pblm. Finally I re assign some other string i expect this time it may generate core dump. But i didn't get any core dump. Can anyone pls explain why its not generating core dump.

int main()
{
   char *ptr;
   ptr =(char*)  malloc (20);
   strcpy(ptr,"MemoryOperations");
   printf("Before Free memory : %s\n",ptr);
   free(ptr);
   printf("After Free memory : %s\n",ptr);
   strcpy(ptr,"MemReassign");
   printf("After Re Assigning : %s\n",ptr);
   return 0;
}

Same code i run by using dbx,

(dbx) check -all
access checking - ON
memuse checking - ON
(dbx) run
Running: a.out 
(process id 19081)
RTC: Enabling Error Checking...
RTC: Running program...
Before Free memory : MemoryOperations
Read from unallocated (rua):
Attempting to read 1 byte at address 0x100101a48
which is 2232 bytes into the heap; no blocks allocated
stopped in _ndoprnt at 0xffffffff671abbf0
0xffffffff671abbf0: _ndoprnt+0x1c04:    call     _PROCEDURE_LINKAGE_TABLE_+0x620 [PLT] ! 0xffffffff67340d20
(dbx) exit
Was it helpful?

Solution

free(ptr) does not modifies the value of the ptr. It just marks that corresponding location is available for reallocation.

A block of memory previously allocated by a call to malloc, calloc or realloc is
deallocated, making it available again for further allocations.
Notice that this function does not change the value of ptr itself, 
hence it still points to the same (now invalid) location.
--cplusplus.com

Hence if you actually want to generate core dump try something sure shot then try something crazy, like:

char d=10/0;  //arithematic

char *a=malloc(1);
free(a);
a=NULL;   //this is important after free.
*a=100;

OTHER TIPS

If you write into memory after it has been freed, anything can happen. It's undefined behaviour. You can get a core dump or not. In your case you don't get a core dump because the memory, even if it has been freed, is still accessible by your process. Buf if you would do another malloc just before the return 0 statement and write into that memory, the string "After Re Assigning ..." will most likely be overwritten.

With dbx, the printf("After Free memory : %s\n",ptr); statement produces a "Read from unallocated" error because you have switched on access checking, but without dbx there is no access checking at all.

For simulating a core dump you can do this :

void main()
{
  char *p = NULL ;
  *p = 'A' ;
}

This will crash on most platforms.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top