-1

我有这样的东西:一个具有分配一些内存的成员函数的类。为什么在函数退出时,指针是否设置为指向 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;
    }
}

然后在主要内部:

    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    
4

3 回答 3

0

调用后,您应该会看到 的实例的Amemoryblock不等于 NULL assignsome

class A
{
private:
    int* memoryblock;
public:
    void assignsome(int n);
};

void A::assignsome(int n)
{
    memoryblock = new int[n];
}

int main () {
    A a;
    a.assignsome(5);
    return 0; // breakpoint here - a.memoryblock isn't NULL
}
于 2013-02-05T13:33:44.660 回答
0

如果你把断点放在那里,调试器仍然没有运行该行。

继续到下一行查看它的分配情况。

于 2013-02-05T13:18:00.010 回答
0

在这种情况下,调试器可能会有点误导。实际上指针不是NULL,调试器只是很困惑,不知道A你在说什么。我建议在类似情况下有疑问时使用调试打印。

于 2013-02-05T13:18:48.497 回答