【发布时间】:2013-02-05 13:13:35
【问题描述】:
我有这样的东西:一个具有分配一些内存的成员函数的类。为什么在函数退出时,指针会被设置为指向 NULL?
class A
{
private:
int* memoryblock;
public:
void assignsome(int n);
};
void A::assignsome(int n)
{
memoryblock = new int[n]; // At this point, debugger suggests memoryblock is not pointing to null.
}
// On exit of this function, memoryblock points to null!
根据要求:这是完整的细分:
int FileHandler::PerValueMemoryBlockRead(char* delimarray, unsigned int sizeofarray)
{
// File Opened and mValues_n calculated.
mValues = new int[mValues_n + 1];
mValuesAllocated = true;
// Assignment of the contents of mValues is done.
mValues[next_value_pos] = 0x0; // Last int set to zero. /// next_value_pos is an int which is incremented. (Code Removed because there is no point showing it.)
return 0;
}
void FileHandler::SerialPrint()
{
if(mValuesAllocated){
std::cout << "Address:" << mValues << std::endl;
std::cout << "Size=" << mValues_n << "B" << std::endl;
for(ull pr = 0; pr < mValues_n; pr ++){
std::cout << (int)mValues[pr] << " ";
}
std::cout << std::endl;
}
else{
std::cout << "Nothing to print. 'PerValueMemoryBlockRead' has not yet been called." << std::endl;
}
}
然后在main里面:
if((!datahandle.PerValueMemoryBlockRead(delimarray, 3))
&& (!converthandle.PerValueMemoryBlockRead(delimarray, 3))
&& dataoutput.is_open()){
dataoutput.seekp(0, std::ios::beg);
// Code
converthandle.SerialPrint(); // SEG FAULT
datahandle.SerialPrint(); // SEG FAULT
// End Code
【问题讨论】:
-
如何检查区块是否为
NULL? -
这将永远发生(如果 new 不起作用,它会抛出)。但是当你退出该方法时。但可能发生的情况是,调试器将不知道您要从哪个 A 实例打印成员
memoryblock。 -
您的程序是否将该指针视为空值?您正在调试发布版本吗?
-
通过完整示例我的意思是sscce。我不想看到导致您出现问题的原始代码,我希望您尝试在一个小示例中重现该问题。这可能会引导你开悟。如果您没有任何反应,请在此处发布。
-
最重要的是,您从 PerValueMemoryBlockRead 的粘贴中删除了代码:您没有显示如何复制数据,这是此类错误代码的典型故障点。
标签: c++ memory null allocation