smsware
smsware

Reputation: 479

How to delete/free a string literal?

I have a std::vector<const char*> which I populate by .push_back("something"). How to delete contents not including std::string's header? delete segfaults, and std::free needs void* and it "cannot initialize [..] with an lvalue of type 'const char *'".

Upvotes: 3

Views: 892

Answers (3)

digito_evo
digito_evo

Reputation: 3672

String literals like "something" are stored in a read-only segment of the executable. You can not delete them. And also, modifying them is undefined behavior.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

String literals have static storage duration. You may not delete them using the operator delete. String literals will be alive until the program ends,

You may delete what was created using the operator new.

You can just erase all or selected elements of the vector or clear it entirely.

Upvotes: 3

eerorika
eerorika

Reputation: 238351

You may delete only what you new. You didn't use new to create the string literals, so using delete on them will result in undefined behaviour. Don't do that. Similarly, you may free only what you malloc (plus a few related functions that malloc internally).

String literals have static storage duration. That means that their storage is deallocated automatically at the end of the program without your intervention.

You can erase the pointers from the vector using the erase member function.

Upvotes: 9

Related Questions