开发者

C++ pointer to string type segmentation fault

开发者 https://www.devze.com 2023-02-01 03:05 出处:网络
I initialize a pointer to stri开发者_JS百科ng type and allocate some memory with malloc function. My problem is when i try to use one of the string pointed by this pointer, i get segmentation fault.

I initialize a pointer to stri开发者_JS百科ng type and allocate some memory with malloc function. My problem is when i try to use one of the string pointed by this pointer, i get segmentation fault.

string anyString = "anyWords";
string *pointerToString;
pointerToString = (string *) malloc(sizeof(string) * 5);
pointerToString[i] = anyString; // this line causes segmentation fault

Thanks in advance for any help.


std::vector<std::string> strings(5);

This is what you actually want.


Avoid using malloc with objects in C++.

Instead, use new:

std::string * str = new std::string("Hello");
// ...
delete str;

For an array:

std::string * tab = new std::string[5];
// ...
delete[] tab; // if you allocated with new[], release with delete[]

The reason it's failing in this case is that malloc, unlike new, does not call the class' constructor. Since std::string allocates memory on its own, then you get an invalid object in the end.

So, new/delete (or new[]/delete[]) is the way to go here. You can still use malloc if you want, but only for "POD" type (primitive types, old style structs, etc.). And if you allocate with malloc, release with free. Don't mix up new and free or malloc and delete (there's an exception to this rule: see Mehrdad Afshari's comment below).


As Etienne said, you should have used new as malloc only allocates memory but does not call constructor which initializes that memory. std::string is a class and when you want to create instance of it on the heap, you must use new, just like for any other class type. You tried to write to a wrong address and therefore your segmentation fault.

You want to create array of strings. In C, you will use array, but in C++ use std::vector.


You probably do not want to be doing it that way but if you are, i.e. using malloc to allocate the memory, then you need to use placement-new.

Actually, this will do placement-new for you.

std::vector< std::string > vec;
vec.reserve( 5 );
vec.resize( 5 );

The call to reserve() allocates the memory for you and then resize() actually creates the objects there in the memory already allocated, with placement-new.

Placement new in the C++ FAQ is documented well here. Read it to learn. Then probably simply use vector.

0

精彩评论

暂无评论...
验证码 换一张
取 消