在循环中第二次调用luaT_pushudata时失败

failed when calling luaT_pushudata for the second time in a loop

本文关键字:pushudata 失败 luaT 调用 循环 第二次      更新时间:2023-10-16

我正在使用lua的c api,遇到了一些问题。

当我做一些循环时,luaT_pushudata总是失败,当我第二次调用它时并说"在0x7ffff7ba85b3处没有lua_newuserdata()的可用源"(在eclipse中调试时)

当直接运行可原谅程序时,它只是说分段故障(核心转储)这是我的部分代码(它们在一个循环中):

// establish the new tuple
tupleA temptupleA;
// cannot delete the buffer_char, the buffer char must be deallocate manually when erase the vector
unsigned char * buffer_char = new unsigned char[rect.width*rect.height*3];
glReadPixels(0, 0, rect.width, rect.height, GL_RGB, GL_UNSIGNED_BYTE, buffer_char);
temptupleA.pic = buffer_char;
temptupleA.action = new double[3];
temptupleA.reward = new double[1];
totalBuffer.push_back(temptupleA);
// set action
// get the Action
double * buffer = charA2fA(totalBuffer[totalStep].pic, raw_width*raw_height*3);
//std::cout<<buffer[raw_width*raw_height*3-1]<<std::endl;// check
THDoubleStorage *mystorage0 =  THDoubleStorage_newWithData(&buffer[0], raw_width*raw_height*3);
THDoubleTensor* mytensor0 = THDoubleTensor_newWithStorage4d(
                    mystorage0, 0,
                    1, raw_width*raw_height*3,
                    3, raw_width*raw_height,
                    raw_width, raw_height,
                    raw_height, raw_width);
lua_getglobal(L, "returnAction");
std::cout<<totalStep; //check
luaT_pushudata(L, (void *)mytensor0, "torch.DoubleTensor"); // there is something wrong
std::cout<<" pass the luaT_pushudata"<<std::endl;
if(lua_pcall(L,1,3,0)) lua_error(L);
d->ctrl[0] = lua_tonumber(L,-3);
d->ctrl[1] = lua_tonumber(L,-2);
d->ctrl[2] = lua_tonumber(L,-1);
totalBuffer[totalStep].action[0]=d->ctrl[0];
totalBuffer[totalStep].action[1]=d->ctrl[1];
totalBuffer[totalStep].action[2]=d->ctrl[2];
lua_remove(L, -1);
lua_remove(L, -2);
lua_remove(L, -3);
THDoubleTensor_free(mytensor0);
delete [] buffer;

那么问题的原因可能是什么呢??

我发现了问题:与其写lua_remove(L,-1)、lua_remove(L,-2)、luon_remove

luaT_pushudata窃取引用,因此您可能会访问释放的内存。用valgrind检查。