【发布时间】:2020-08-28 18:12:21
【问题描述】:
我正在学习指针和结构,但我遇到了这个难以理解的问题。 我创建了这个简单的程序用于测试目的:
#include <iostream>
struct testStructure
{
int a = 0;
int b = 0;
int c = 400;
};
int main()
{
struct testStructure* testStruct;
testStruct = new testSctructure;
std::cout << testStruct->c;
delete testStruct;
return 0;
}
上面的程序工作得很好,它打印出值 400。但是当我尝试用 malloc 来做时:
#include <iostream>
struct testStructure
{
int a = 0;
int b = 0;
int c = 400;
};
int main()
{
struct testStructure* testStruct;
testStruct = (testStructure*)malloc(sizeof testStructure);
std::cout << testStruct->c;
free(testStruct);
return 0;
}
它给了我这个值: -842150451
为什么? 上述示例是在 Visual Studio 2019 中编写和构建的。
我知道在 C++ 中你几乎应该总是想使用 new 关键字,但我想尝试一下。
【问题讨论】:
-
第二种情况,你已经分配了内存,但是还没有初始化。未定义的行为。
-
-842150451是一个神奇的调试代码。0xcdcdcdcd看这里是什么意思:https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations
标签: c++ pointers malloc new-operator