【问题标题】:Please help me in understanding the above code behaviour.Understanding Void Pointers & double void Pointer Manipulation请帮助我理解上面的代码行为。理解空指针和双空指针操作
【发布时间】:2013-11-22 12:13:59
【问题描述】:

大家好,请花点时间@查看下面的代码 sn-p:

#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. 无效*ptr = NULL;在 main 中,我将此指针分配给 NULL。 Ptr 指向位置 0x0 。 Ptr 的地址是 0x28ff40
  2. func((void**)&ptr);在这里我用双指针对它进行类型转换 在函数() { 我动态分配一些内存。所以 Ptr 指向某个地址,即 0x7e36d8
    }
  3. func2(void* ptr1) 在这里我感到困惑:当我打印 ptr 时:它给了我 0x7e36d8 而不是 0x28ff40 所以当我让 ptr = NULL; location 的内容为 NULL 而不是 @ 0x28ff40。

第一个问题:我应该修改什么以使内容@ location 0x28ff40 = NULL 第二个问题:我搞砸了类型转换,我不明白我是如何错过基地址的:0x28ff40

请帮助我理解这一点。

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

提前谢谢大家!!!

【问题讨论】:

  • 请告诉我:投反对票的标准是什么!! ???问题出在哪里???????
  • 在正常情况下,你不应该在 C++ 中使用void*

标签: c++ casting void-pointers


【解决方案1】:

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

修改func2()func() 一样工作:

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

然后这样称呼它:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多