Search code examples
cdebuggingdbx

After Free pointer memory i can re assign value


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

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;