Hi,
In the code snippet below, the program gets crashed at delete operator.What would be the possible cause, after doing lots of modification with this code. I had guessed that char* are managed by the compiler and there's no need for memory allocation.
But I didn't find any reason to this thought. Please let me know what the actual thing is going behind the scene.
Thanks.
Don't guess, but reread the chapter about memory allocation in your book. In the meantime, use std::string.
tmpCString = "vivek Kumar\n"; is not valid C++, because "vivek Kumar\n" is a string literal, i.e. a constant char array. You cannot cast it to a pointer to non-const char. Even if tmpCString were a pointer to const char, you'd have a memory leak here, because you're manually creating a char using new, but then overwrite the address with that of the string literal.
Next, delete tmpCString; is also incorrect. You may never use delete on a string literal (or any other address that was not returned by the new operator). To delete an array (that was created with new[]) you need to use operator delete[] anyway. tmpCString = '\0'; makes no sense either. '\0' is a character, but tmpCString is a pointer. This still works, because '\0' can be converted to a null pointer, but you should write tmpCString=0; or tmpCString=NULL; in the first place, which is common practice.
Thanks for pointing me out that tmpCString = "vivek Kumar\n"; is not a c-string rather its a const char array.
But if you dont mind I would you to know is it right to use the below code as I'm still having doubt about this.
1 2 3 4
char * someCharPtr = "something" ; // this true as it's a initialization
someCharPtr = "something new again";
so while assigning someCharPtr for second time again, is this right thing.
In this: char someCharArray[] = "something";
someCharArray is not a pointer, it's a char array.
The code is equivalent to char someCharArray[10]={'s','o','m','e','t','h','i','n','g','\0'};