int main()
{
char *name = new char[7];
name = "Dolphin";
cout << "Your name is : " << name <<endl;
delete [] name;
}
Why doesn’t the VC++ compiler complain?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’ve got two questions here:
First, What’s wrong with code? Well …
When you assign “Dolphin” to name you are not copying into the allocated array you are adjusting the pointer to point to a string literal. Later you try to delete what the pointer points to. I’d expect this to crash horribly in some environments.
If you really want a copy of the “Dolphin” characters, have a look at strncpy(), but as already been observed, you need a space for the null too.
Second, why that particular compiler doesn’t warn you that the assignment is potentially: that’s a bit harder. [It’s been observed that other compilers will give a warning.] The question is whether this compiler treats a string literal as a “Pointer to const char” or a “Pointer to char”.
If it was the former case then I’d expect an error. Until about 2004 C++ was consistent with C in treating literals as pointer to char, and hence the assignment would be permitted. So I guess the question for you is to determine what version of the specs you are working against, and that might depend upon the version of VC++ you are using and also any compiler options you have chosen.
A MSDN C++ reference indicates that VC++ treats string literals as non const. I’ll leave it to VC++ gurus to comment further.