fbpx

C++: Create an Object at a Given Address

Bjarne-stroustrup
 

In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.

Task

Show how language objects can be allocated at a specific machine addresses.

Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary). For example, create an integer object. Print the machine address of the object. Take the address of the object and create another integer object at this address. Print the value of this object to verify that it is same as one of the origin. Change the value of the origin and verify it again.

C++ supports this natively through placement new. This allows construction of complex object types in arbitrary memory locations.

#include <string>
#include <iostream>

int main()
{
	// Allocate enough memory to hold an instance of std::string
	char* data = new char[sizeof(std::string)];

	// use placement new to construct a std::string in the memory we allocated previously
	std::string* stringPtr = new (data) std::string("ABCD");

	std::cout << *stringPtr << " 0x" << stringPtr << std::endl;

	// use placement new to construct a new string object in the same memory location
	// remember to manually call destructor
	stringPtr->~basic_string();
	stringPtr = new (data) std::string("123456");

	std::cout << *stringPtr << " 0x" << stringPtr << std::endl;

	// clean up
	stringPtr->~basic_string();
	delete[] data;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.

RSS TFE Times