Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc for string pointers: how it can be disastrous?

Tags:

c++

string

malloc

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 :

  • Pointers are PODs. Then why it is called non-POD here? (Maybe I have to understand POD better.)
  • How can this be so disastrous? (I guess I have to understand string Internals for this.)

Please explain!

like image 905
Swathi Appari Avatar asked Sep 15 '26 01:09

Swathi Appari


2 Answers

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;
like image 53
Luchian Grigore Avatar answered Sep 17 '26 20:09

Luchian Grigore


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++. :)

like image 26
HostileFork says dont trust SE Avatar answered Sep 17 '26 21:09

HostileFork says dont trust SE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!