Home > OS >  How to delete/free a string literal?
How to delete/free a string literal?

Time:01-27

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 *'".

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • Related