为什么使用 'new' 创建的数组设置为 NULL?
Why does array created with 'new' become set to NULL?
我有这样的东西:一个带有成员函数的类,它分配一些内存。为什么在函数退出时,指针会被设置为指向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
如果将断点放在那里,调试器仍然没有运行该行。
继续到下一行以查看其已分配。
在这种情况下,调试器可能会有点误导。事实上,指针不是NULL,调试器只是感到困惑,不知道您在说哪个A
。我建议在类似情况下有疑问时使用调试打印。
在调用assignsome
:后,您应该看到A
的实例的值memoryblock
不等于NULL
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
}
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 如果我在相应 char 数组的声明中为其提供额外的元素,是否会自动设置 NULL?
- C++ 由于类析构函数中的指针设置为 NULL 而导致的内存泄漏
- 删除对象与将指针设置为 null
- 在单一实例类中将成员指针设置为 null 的正确方法是什么
- STD :: Sort将数组指针设置为NULL
- 设置 NULL 会导致滞后,[MAX_STRING_LENGTH] = {'\0'};
- 一旦对象设置为 null,用于声明对象的堆大小的变量就设置为 null?
- 将结构元素地址设置为C 中的null(单链接列表)
- 移动语义是否只是一个浅层副本并将其他人的指针设置为 null?
- 删除指针并将指针设置为null之间有什么区别
- 为什么我们需要在move构造函数中将右值引用设置为null
- 将数组中的元素设置为 0 或 NULL
- SQLBindParam:设置 Null 值失败 (ODBC)
- 如果指针设置为 NULL,则对它的任何引用都不会或通过它也是 NULL
- WCHAR_T设置为c 中的null
- 当我要删除它时,指针甚至无法设置为null
- 将对象的数组设置为c 中的null
- 智能指针:通过引用设置、重置、设置null、null检查或重置检查
- c++无法为包含静态变量的对象设置NULL指针