在新线程中处理类时的内存分配问题

Memory allocation problems when working with a class in a new thread

本文关键字:内存 问题 分配 处理 新线程 线程      更新时间:2023-10-16

我有这样的代码:

#include "Item.h"
#include "Object.h"
int main(){
    Item Pan(0);
    Pan.Prep2Cook();

    //Object(char*, int);
    Object Drawer(Pan.Oil_Memory, Pan.Oil_Size);

    Drawer.Search();
    Pan.OilId = Drawer.Oil();
    Pan.Finish_Cooking();

    return 0;
}

它像预期的那样工作,但是如果我把它改成这样:

#include "Item.h"
#include "Object.h"
DWORD WINAPI Cooky(LPVOID);

int main(){
    // tried changing to 1000000000, still gives the error...
    // tried changing to 0, still gives the error...
    CreateThread(0,100000,Cooky,LPVOID(0),0,0);
    /*...
    Do_Other_Stuff();
    ...*/

    return 0;
}
DWORD WINAPI Cooky(LPVOID lParam)
{
    Item Pan(int (lParam) );
    Pan.Prep2Cook();
    Object Drawer(Pan.Oil_Memory, Pan.Oil_Size);//memory allocating error here
    Drawer.Search();
    Pan.OilId = Drawer.Oil();
    Pan.Finish_Cooking();
    return 0;
}

在"Drawer"类中分配内存时会出现这样的问题:

data1 = new unsigned char[size];//error here
data2 = new unsigned char[size2];
all_data = new unsigned char*[9];

编辑:size和size2等于或小于10000

我试图"机动"与dwStackSize参数在Createthread,但它仍然给我错误…

欢迎提供解决此错误的建议。

用这么少的代码很难判断你的错误是什么,但这里有一些事情你可能需要考虑

你的主线程在

中实际在做什么
/*...
Do_Other_Stuff();
...*/
return 0; //this will immediatly end every single thread

很重要,如果您尝试按此方式运行代码,则主线程将结束并退出程序如果在分配内存失败时程序似乎崩溃了,这可能是因为这是线程中的一个重要操作,当您尝试分配内存时程序退出

其次,你分配给线程的堆栈大小是无关的,因为失败的分配是在堆上的(因为你使用new)进一步,分配到太多的堆栈可能会阻碍分配,因为你只有有限的内存(但这可能不是问题)