在循环

时间:2016-04-18 13:11:28

标签: c++ api lua

我正在使用lua的c api而且遇到了一些麻烦。

当我做一些循环时,luaT_pushudata总是在我第二次调用时失败并且说  '没有可用于lua_newuserdata()的源位于0x7ffff7ba85b3 ' (在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;

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

2 个答案:

答案 0 :(得分:0)

我找到了问题:而不是写lua_remove(L,-1),lua_remove(L,-2),lua_remove(L,-3)我应该简单地写lua_pop(L,3)或写lua_remove(L ,-1)三次

答案 1 :(得分:0)

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