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.
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.