gpt4 book ai didi

c++ - C++为什么new关键字有效而malloc无效?

转载 作者:行者123 更新时间:2023-12-01 15:10:11 25 4
gpt4 key购买 nike

我正在学习有关指针和结构的信息,遇到这种难以理解的问题。
我创建了这个简单的程序用于测试:

#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;
}
它给了我这个值(value):
-842150451
为什么?
以上示例是在Visual Studio 2019中编写并构建的。
我知道在C++中,您几乎总是应该使用new关键字,但我想尝试一下。

最佳答案

new使用类的构造函数初始化分配的内存(在这种情况下是隐式的)。malloc不执行初始化,它只分配一部分内存。读取未初始化的内存将具有未定义的行为。

关于c++ - C++为什么new关键字有效而malloc无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63638955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com