Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

placement new equivalent in C

Does an equivelent to C++'s placement new exist in C? I mean, can an object be constructed at a specified location in C? Can realloc() be used for that?

like image 874
TeaOverflow Avatar asked Dec 03 '22 00:12

TeaOverflow


2 Answers

Placement new simply skips allocation and constructs an object in preallocated memory. Since C lacks constructors, there is no need for placement new. I suppose the equivalent would be a pointer typecast, because once you have a pointer, you can act as if an object exists.

Example of carving objects of differing type from a common memory pool:

char *pool = (char *) malloc( 1000 );
char *pen = pool;

foo *obj1 = (foo *) pen;
pen += sizeof (foo);

bar *obj2 = (bar *) pen;
pen += sizeof (bar);

/* etc */

Of course, in doing this, you take responsibility for passing the right pointer to free, and looking after alignment requirements — just like placement new in C++.

like image 163
Potatoswatter Avatar answered Dec 25 '22 14:12

Potatoswatter


Since C doesn't have anything like a constructor, you can simply take the address and cast it to a pointer to the type you want to use. Of course, you need to ensure proper alignment, or that can fail (but the same is true with placement new in C++).

like image 36
Jerry Coffin Avatar answered Dec 25 '22 16:12

Jerry Coffin