当前位置:网站首页>malloc和new之间的不同-实战篇
malloc和new之间的不同-实战篇
2022-07-27 05:19:00 【Mr FF】
很多人在面试时都会被问malloc和new之间的不同,有些人会说一下。但很多人可能并没有真正的遇到过因其不同而带来的问题。
1 new会调用构造函数,malloc不会。
这句话的真正意思是,new会给struct的成员分配空间,而malloc其实则不一定。
struct Data {
string name;
int id;
};
struct Data* pData = (Data*) malloc(sizeof(Data));
if (pData == nullptr) {
return;
}
pData->name = "test"; // crash
Data* pData = new Data();
pData->name = "test"; // ok2 假如你的结构体中有string,又有零长数组,你改如何做?
struct Data {
string name;
int id;
char data[0]; // zero array
};
struct Data* pData = (Data*) malloc(sizeof(Data));
if (pData == nullptr) {
return;
}
pData->name = "test"; // crash
Data* pData = new Data();
pData->name = "test"; // ok
char source[20] = {'h', 'a', ...};
memcpy(pData->data, source, 20); // crash.
new的问题在于,它没法给你的零长数组分配空间。除非你自己定义构造函数,但也不行。
因为零长数组中index 0,即data[0]是占位用的,你一开始不给它分配空间,后面就是左值,
无法再将其指向其它地址了。
边栏推荐
- 2021中大厂php+go面试题(2)
- 13.逻辑回归
- Public opinion & spatio-temporal analysis of infectious diseases literature reading notes
- 14.实例-多分类问题
- 2. Simple regression problem
- Performance optimization of common ADB commands
- Global evidence of expressed sentimental alterations during the covid-19 pandemics
- 1.PyTorch简介
- 舆情&传染病时空分析文献阅读笔记
- GBASE 8C——SQL参考6 sql语法(10)
猜你喜欢

5. Indexing and slicing

19. Up and down sampling and batchnorm

13. Logistic regression

视觉横向课题bug1:FileNotFoundError: Could not find module ‘MvCameraControl.dll‘ (or one of it

【mysql学习】8

3. Classification problems - initial experience of handwritten digit recognition

7.合并与分割

【12】理解电路:从电报机到门电路,我们如何做到“千里传信”?

14. Example - Multi classification problem

10.梯度、激活函数和loss
随机推荐
Digital image processing Chapter 2 fundamentals of digital image
Auto Encoder(AE),Denoising Auto Encoder(DAE), Variational Auto Encoder(VAE) 区别
常用adb命令汇总 性能优化
数字图像处理 第二章 数字图像基础
Rk3399 GPIO port how to find which GPIO port it is
pytorch中交叉熵损失函数的细节
Digital image processing -- Chapter 9 morphological image processing
Digital image processing Chapter 4 - frequency domain filtering
GBASE 8C——SQL参考6 sql语法(2)
GBASE 8C——SQL参考6 sql语法(15)
Uboot supports LCD and HDMI to display different logo images
4. Tensor data type and creation tensor
Day 11. Evidence for a mental health crisis in graduate education
[MVC Architecture] MVC model
Global evidence of expressed sentimental alterations during the covid-19 pandemics
12.优化问题实战
go通过channel获取goroutine的处理结果
模型的推理速度
数字图像处理——第九章 形态学图像处理
14.实例-多分类问题