memory allocation problem | Sololearn: Learn to code for FREE!

+1

memory allocation problem

I am a beginner in c++ program I faced a problem showing segment failure. my code is: int main(){ string *ptr; ptr = (string*) malloc(sizeof(string)); cin >> *ptr; free(ptr); }

5/3/2021 4:47:56 PM

Soomeet Kumar

1 Answer

New Answer

0

In C++ you should use the 'new' keyword to allocate memory in the heap instead of malloc(). Instead of doing string* ptr = (string*)malloc(sizeof(string)); you can just do: string* ptr = new string; and to free memory you don't use the free() function, you use the 'delete' keyword. Instead of free(ptr); you type: delete ptr; The malloc function might be in C++ (i'm not sure) but from what I've read, you should rarely use it, and should just use 'new' instead.