Swathi Appari
Swathi Appari

Reputation: 193

malloc for string pointers: how it can be disastrous?

In this Informit C++ guide, I read this:

Using malloc() to create a non–POD object causes undefined behavior:

//disastrous!
std::string *pstr =(std::string*)malloc(sizeof(std::string));

I didn't understand 2 points here :

Please explain!

Upvotes: 3

Views: 1848

Answers (2)

Here you are allocating a standard string, not allocating a pointer to a standard string. Note that you are passing sizeof(std::string) to malloc; that is how much memory you are getting back...note the size of the object is bigger than the size of a pointer. If you were only allocating a pointer, you'd expect the size passed in to be sizeof(std::string*).

The pointer you receive back is how you keep track of the result of the allocation, but that pointer isn't living on the heap. Here it's just being stored in an ordinary variable. Had you allocated a pointer instead, then your variable to keep track of it would need to be a pointer-to-a-pointer.

Anyway, if you wanted to, you could legally allocate a pointer to a standard string like this:

std::string str;
std::string** ptr_to_pstr = (std::string**)malloc(sizeof(std::string*);
*ptr_to_pstr = &str;

Why you would want to is not entirely clear. But neither is it clear why you'd use malloc in C++. :)

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258618

pointers are PODs then why here it is called non-POD

It's not talking about the pointer, but the std::string.

It's disastruous because malloc doesn't call the constructor, so you'll have pstr a std::string pointer that points to a std::string that wasn't properly constructed. The memory was allocated but it wasn't initialized properly, because of the missing constructor call.

The correct way is

std::string *pstr = new std::string;

The clean way is to just have a variable in automatic storage:

std::string str;

Upvotes: 5

Related Questions