Reputation: 31
On page 113, in The C++ Programming Language (Third Edition and Special Edition), Stroustrup states:
struct address {
char * name ; // "Jim Dandy"
long int number ; // 61
//...
};
void f ()
{
address jd ;
jd.name = "Jim Dandy"; // Is this possible?
jd.number = 61 ;
}
Is this possible since there was not any memory allocated for the char* field of jd?
Update: Thank you all for your answers! Given that it's not safe, I won't use it. It just caught my attention when I saw it in the book.
Upvotes: 1
Views: 146
Reputation: 254461
The memory was allocated: enough for a pointer. Now that points to the static array that contains the string.
If you were expecting it to put a copy of the string in the structure, then that's not how C-style strings work; if you want that behaviour, then use the C++ std::string
class instead.
I hope the example goes on to explain how dangerous this is. The static array is constant, but a quirk of the language means you're allowed to assign a non-const
pointer to point to it. This allows you to write code that attempts to modify a constant object, which gives undefined behaviour at run time:
jd.name[0] = 'T'; // BOOM! Undefined behaviour.
If you're lucky, the compiler might warn you about that mistake. You can prevent it by declaring the pointer const
:
char const * name;
...
jd.name[0] = 'T'; // Gives a friendly compile-time error
Upvotes: 2
Reputation: 363577
Enough memory is allocated to hold a pointer to char
, and the assignment sets the pointer to point to a static buffer holding the string "Jim Dandy"
, so yes, this is possible. No allocation is needed since the string is not copied.
(However, setting a char*
to a string literal is deprecated; use a char const*
instead.)
Upvotes: 2