当传递的内存指针不足时放置新的
我只是想知道当传递一个不足以分配的缓冲区时,放置 new 会如何表现。但看起来无论如何都成功了。这是我的代码:
#include <stdio.h>
#include <malloc.h>
#include <new>
class MyClass
{
public:
char data;
char data1;
};
int main() {
printf("sizeof MyClass: %lu\n", (unsigned long)sizeof(MyClass));
void *place = malloc(sizeof(MyClass) - 2);
MyClass *ptr = new (place) MyClass();
ptr->data = 10;
ptr->data1 = 20;
printf("%d\n", ptr->data1); //This seems to have work fine, storing the data as always
}
这是预期的行为吗?有人请解释一下这是如何工作的。谢谢。
PS:我使用的是64位Ubuntu系统,g++编译器。
I was just wondering how placement new would behave when it is passed a buffer thats not sufficient for allocation. But it seems like it succeeds anyway. Here's my code:
#include <stdio.h>
#include <malloc.h>
#include <new>
class MyClass
{
public:
char data;
char data1;
};
int main() {
printf("sizeof MyClass: %lu\n", (unsigned long)sizeof(MyClass));
void *place = malloc(sizeof(MyClass) - 2);
MyClass *ptr = new (place) MyClass();
ptr->data = 10;
ptr->data1 = 20;
printf("%d\n", ptr->data1); //This seems to have work fine, storing the data as always
}
Is this the expected behavior? Somebody please explain how come this works. Thanks.
PS: I'm using a 64 bit Ubuntu system, g++ compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在对于该类型来说不够大的内存块上调用新的放置是未定义的行为。它可以(并且可能在真实的程序中)破坏你的堆。
未定义的行为是未定义的,因此程序可以看起来正常进行,即使您可能会浪费不属于您的内存。您的简单示例甚至没有尝试释放它分配的内存,因此您从未真正测试堆以查看它是否已损坏。
Calling placement new on a block of memory that isn't big enough for the type is undefined behavior. It can (and likely will in a real program) trash your heap.
Undefined behavior is undefined, so the program can appear to proceed as normal, even though you're likely trashing memory that doesn't belong to you. Your simple example doesn't even attempt to free the memory it allocated, so you never really test the heap to see if it was corrupted.
安置新与分配无关。它不知道也不关心你传递的缓冲区有多大——实际上,它唯一的工作是调用一个对象的构造函数,该对象将开始分配(并且可能适合)你传递给它的地址。
Placement new has nothing to do with allocation. It doesn't know nor does it care how big the buffer you pass is - its only job, really, is to call the constructor on an object that shall begin its allocation (and presumably fit at) the address you passed to it.