Click here to Skip to main content
15,890,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a confusion with the member function string::c_str().
Does it create a new char array, copies the contents then returns the pointer of the initial element ? or just a pointer to the already created array ?
But if so, why a code like the one below won't destroy the string object?

C++
string s = "Hi Sam";
const char *c = s.c_str();
delete c;


Thanks, Sam.
Posted
Comments
Philippe Mori 12-Dec-15 23:05pm    
There are tools and compiler options to help find such problems but it is better to never write undefined code to start with and a good way to do so is to avoid explicit memory allocation and desallocation as it is error prone.

This is really a question you should solver yourself bei googling for the answer.

Explained means it, that it returns the pointer to the inner string of the object. So it is NOT a new object or memory block.

Use the detail view of your debugger to see the inner guts of objects.
 
Share this answer
 
Comments
Samuel Shokry 12-Dec-15 13:40pm    
First of all thanks for your reply.
I have googled it, and I understood that it is a pointer to the inner data, but what about calling delete, why doesn't it cause any problem to the string object ?
The code you presented could do just about anything in a C++ program - its behaviour is undefined.

So what makes it undefined? Two things in this case:

- you're deleting something that hasn't been allocated by new
- You're deleting an array using the wrong form of delete

So unless the contract for a class tells you to delete something, DON'T!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900