Archived

This topic is now archived and is closed to further replies.

KevinG

Can you accidentally overwrite something on the stack like this?

Recommended Posts

char * c_ptr = "Hello, World!"
cout <<&c_ptr; //lets say the address is 12, for example
c_ptr = "Oh, no!  My world is ending!  This string is much larger than the previous one!  How am I not overwriting anything near me?";
 
If the program thought this was "Hello, World!" at first, wouldnt it find a spot just big enough for "Hello, World!"? If this is so, wouldnt setting c_ptr to the second string overwrite data near where "Hello, World" used to be since it''s being set in the same place (I assume) and it''s much larger? I dont know...this is confusing. I was thinking about doing strings this way but I don''t know if I could accidentally overwrite something important. Thanks for any help.

Share this post


Link to post
Share on other sites
In the data portion of your program the two strings will reside, both ending in a null as c-strings do.

the first line will assign c_ptr to the address of the string "Hello, World!" and the third line will assign it the address of the other, longer string.

So, you see, there is no problem. All the space for literals are actually assigned at compile time, and all your code does it point to different strings. In C or C++, a literal string actually just resolves to a char const * to the location of that string.

Share this post


Link to post
Share on other sites
The compiler will embed both of those string literals in the resulting executable file itself. So in effect, all you''re doing is changing what the pointer points to. (Just like ironfroggy said).

Share this post


Link to post
Share on other sites
Ah, thanks. I thought it printed them out in the same place because whnen I did cout << c_ptr it was the same address. But of course it was--the address of the pointer never changed. Heh. Im so stupid.

This leads to a new question, though. How do I see the address that the pointer is pointing to using cout?

As far as I know, I can only do this:

cout << &c_ptr; //prints the address of the pointer
cout << c_ptr; //prints the entire string
cout << c_ptr + n; //prints on from the Nth letter in the string
cout << *c_ptr; //should print the first letter of the string...I think.

Is there a way to print the address the pointer is holding?

Share this post


Link to post
Share on other sites
Casting it to unsigned char should be better (unsigned chars are considered numbers, not characters). Won't casting a char array to an int* cause some very nasty bugs? (int's are 4 char-lengths (bytes) on my computer, so the indices would be every 4, not every 1)
EDIT: nevermind, I just realised that you were talking about printing the address of the array.

[edited by - brassfish89 on January 24, 2004 7:21:35 PM]

Share this post


Link to post
Share on other sites