请帮助我理解上述代码行为。了解 void 指针和双 void 指针操作

Please help me in understanding the above code behaviour.Understanding Void Pointers & double void Pointer Manipulation

本文关键字:指针 void 了解 操作 帮助 代码      更新时间:2023-10-16

大家好,请花点时间@查看下面的代码片段:

#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;   
}

请帮助我理解以上代码行为。我更感兴趣的部分是"为什么ptr指针没有被分配NULL值&它用于第二次释放内存"

我的观察:

  1. void*ptr=NULL;在主要情况下,我将此指针指定为NULL。Ptr指向位置0x0。Ptr的地址是0x28ff40
  2. func((void**)&ptr);我用双指针打字在func()中{我动态地分配一些内存。因此Ptr指向某个地址,即0x7e36d8
    }
  3. func2(void*ptr1)这里我感到困惑:当我打印ptr时:它给我的是0x7e36d8,而不是0x28ff40所以当我使ptr=NULL时;位置处的内容为NULL,而不是@0x28ff40

第一个问题:如果内容@location 0x28ff40=NULL,我应该修改什么第二个问题:我搞砸了打字,我不明白我是怎么错过了基本地址的:0x28ff40

请帮助我理解这一点。

注意:请忽略返回值验证。请忽略C/C++风格混合使用的情况。不要建议更改函数Argument。

提前感谢大家!!!

您需要将ptr的地址传递给调整后的func2()

修改func2()以类似func():

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

然后这样称呼它:

res = func2((void**)&ptr);