【问题标题】:Array Created Statically in DLL Gets Overwrittend by calling Program在 DLL 中静态创建的数组被调用程序覆盖
【发布时间】:2011-07-31 16:18:34
【问题描述】:

我有一个使用动态 DLL 的主程序 (PMAIN)。假设 PMAIN 使用 DLL 导出的 2 个函数(foo1、foo2 和 foo3)。函数是这样的:

int __stdcall foo1(){
  str = new MyStruct;
}
int __stdcall foo2(){
  str.LC->objF1();
}

int __stdcall foo3(int val){
  str.LC->objF2(val);
}

MyStruct 是这样的:

struct MyStruct{
  MyObject LC
}

而我的对象是:

class MyObject{
 private:
  int arr1[100];
  int arr2[100];
  int Index;
 public:
  MyObject();
  ~MyObject();
  void objF1();
  void objF2(int val);
}

void MyObject::objF1(){
  for(int i=0;i<100;i++){
    arr1[i]=1;
  }
}

void MyObject::objF2(int val){
  Index++;
  arr2[Index]=val;
}
MyObject::MyObject(){
  for(int i=0;i<100;i++){
    arr1[i]=0;
    arr2[i]=0;
  }
  Index=-1;
}

从 PMAIN 我首先调用 foo1 然后 foo2 然后我循环 100 次调用 foo3;数组 arr1 得到正确更新并在 PMAIN 的整个执行过程中“保留”该值,而每次我调用 foo3 数组 arr2 只包含归零它会被更新,当程序再次调用 foo3 时,它又是空白的。 PMAIN 如何覆盖 DLL 中数组的地址(我在调试时看到了这种行为)。

你知道这怎么可能?

PMAIN 和 DLL 不是应该在内存中的两个不同位置吗?

【问题讨论】:

    标签: c++ dll memory-management overwrite


    【解决方案1】:

    在您的 DLL 中创建的变量与程序使用的变量相同,因此如果您的程序中出现错误,它可以覆盖它们。

    这对我来说看起来不对:

    int __stdcall foo1(){
      str = new MyStruct;
    }
    int __stdcall foo2(){
      str.LC->objF1();  
    }
    
    int __stdcall foo3(int val){
      str.LC->objF2(val);
    }
    

    如果 str 是一个指针,(因为你是新的)那么你需要使用 operator-> 来访问它的成员。像这样:

    int __stdcall foo1(){
      str = new MyStruct;
    }
    int __stdcall foo2(){
      str->LC.objF1();
    }
    
    int __stdcall foo3(int val){
      str->LC.objF2(val);
    }
    

    并且由于 LC 不是指针,而只是结构中的自动变量,因此需要使用 . operator。如上所述。

    【讨论】:

    • 对不起,你是对的,我把operator->和operator的位置颠倒了。在写帖子时,但在源代码中它们就像你说的那样。
    • 顺便说一句,PMAIN 从不做类似的事情:arr2[n]=0;但是 arr2[n] 指向的值发生了变化
    • @Daniele:您的问题并不完全清楚,所以我缺少重要信息,请在您的问题中添加信息,以便我们知道我们在看什么。
    猜你喜欢
    • 2019-03-02
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2011-02-24
    相关资源
    最近更新 更多