-1

Hi All Please spend some time @ looking the code snippet below :

#include <iostream>
#include <stdlib.h>


using namespace std;
int func2(void* ptr1)
{
    cout << " IN Func2" << endl;
    if(ptr1)
    {
     //i freed this Pointer.       
     free(ptr1);       
     ptr1 = NULL;           
     cout << "PTR MADE NULL" << endl;
     return 1;
    }
}

int func(void** ptr1)
{
 cout << " IN Func" << endl;   
 int *ptr2 = (int*)malloc(10*sizeof(int));

 if(ptr1)
 {
 *ptr1 = ptr2;        
 cout << " NOT NULL" << endl;
 return 1;
 }
 else
 {
 cout << " NULL " << endl;         
 return 0;
 }
}

int main()
{    
 int res = 0;
 void *ptr = NULL;   
 func((void**)&ptr);
 res = func2((void*)ptr);
 if(res)
 {
   //Expecting this to be updated with NULL.. surely not working 
   if(ptr)
   {
   //why I'm Coming here       
   cout << "Freeing Ptr for 2nd time " << endl;       
   free(ptr);     
   }
 }
 cin.get();
 return 0;   
}

Please help me in understanding the above code behaviour. I am more interested in the part "Why the ptr pointer is Not getting assigned NULL value & it goes for freeing the memory second time"

My Observations:

  1. void *ptr = NULL; In main i assign this Pointer to NULL. Ptr Points to Location 0x0 . Address of Ptr is something 0x28ff40
  2. func((void**)&ptr); Here i am typecasting this with double Pointer in func() { I dynamically allocate some memory. So Ptr points to some Address i.e 0x7e36d8
    }
  3. func2(void* ptr1) here i get confused : when i print ptr : it gives me 0x7e36d8 and not 0x28ff40 so when i make ptr = NULL; the contents at location are NULL and not @ 0x28ff40.

First question: what should i modify in case to make the contents @ location 0x28ff40 = NULL Second Question : I am messed up with typecasting and i dont understand how i missed the base address : 0x28ff40

Please kindly help me in understanding this.

Note : Please ignore the return values validations. Please Ignore cases of C/C++ style Mix usage. Do Not suggest changes in function Argument.

Thanks People in Advance !!!

Chris
  • 2,955
  • 1
  • 30
  • 43
user2598064
  • 157
  • 1
  • 13

1 Answers1

1

You need to pass the address of ptr to an adjusted func2().

Modify func2() to work like func():

int func2(void** ptr1)
{
  cout << " IN Func2" << endl;
  if(*ptr1)
  ...

Then call it like so:

res = func2((void**)&ptr);
alk
  • 69,737
  • 10
  • 105
  • 255