Dealing with chars in C++ (without std::string)
Question
I have this code:
char* value = "abcdefg";
char* secondValue = value;
The second value will get the addres of value ok? If I delete "value" the secondValue won't be available am I right?
so I should do:
char* value = "abcdefg";
secondValue = new char[strlen(value)];
strcpy(secondValue, value);
so If I delete "value" no problem.
And finally to dealloc the secondValue I should do:
delete[] secondValue;
am I right?
No correct solution
OTHER TIPS
There are two issues with what you wrote:
You cannot delete
char *value = "abcdefg";
, as it is not allocated on the heap. To allocate heap memory you usenew
(in C++) ormalloc
(in C).When you allocate memory for a string, you always need one more extra byte for the null termination.
In your case, you should have done:
secondValue = new char[strlen(value)+1];
Other than that, you are correct
If you are using C++ you are correct, except that you need to make secondValue
one character bigger:
secondValue = new char[strlen(value) + 1];
C-style strings are terminated with a '\0'
character, which also need space to be stored.
If you are using C instead of C++, there is no new
or delete[]
and you have to use the functions malloc()
and free()
instead:
secondValue = malloc(strlen(value) + 1);
...
free(secondValue);
In any case note that in the example value
is a string literal, which cannot be deleted/freed. You should only delete/free what you allocated with new/malloc respectively.
The way you wrote your code:
char* value = "abcdefg";
The compiler will generate a static string "abcdefg"
, and value
will be a pointer to that. You may assign secondvalue = value
and then have value go out of scope, and
secondvalue` will still be valid.
In your example there is no other way to deallocate value
.