SzloseProgramming
SzloseProgramming

Reputation: 45

C++ Dynamic Memory Allocation - char*

I'm having a problem understanding a part of dynamic memory allocation in C++.

I know its standard practice to do something like this to avoid memory leak:

double* pvalue  = NULL; // Pointer initialized with null
pvalue  = new double;   // Request memory for the variable
*pvalue = 29494.99;  
delete pvalue; 

However, I've seen lots of source code like this and delete was never used there to free up memory:

char* text = "something";

So the question is simple: should I use delete EVERY time I no longer need a char pointer (or ANY other)? Or are there some exceptions?

I've read alot and I'm only getting more confused so I hope somebody can help me.


EDIT:

Thank you for explanation. Finally I understand and I can make changes to my source code without worrying!

Upvotes: 0

Views: 992

Answers (1)

You should delete everything you create with new, and nothing else.

char* text = "something";

This does not create something with new, so you shouldn't delete it.

In fact, that statement doesn't create anything (apart from a pointer) - it sets text to point to a string that was created when your program started.

Upvotes: 3

Related Questions