+ 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); }
1 Resposta
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.