Link to home
Start Free TrialLog in
Avatar of bugsbunny1
bugsbunny1

asked on

Could memory be trashed if string "hello" is assigned during declaration?

I know memory could be trashed with this:

char *str1;

str1 = "hello";

... but could anyone confirm whether the following may also cause memory to be trashed or, is the following okay, as it's assigned during declaration?

char *str1 = "hello";

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of Mayank S
Mayank S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oferh
oferh

both cases may cause memory corruption since
the memory allocated for the string is allocated
on the program stack.
that means that when you will exit the function in
which it was allocated this memory is "free".
Ya, if you put this in a function and attempt to return it, it will lead to memory corruption because the activation record of the function will be deallocated and the memory location pointed to by str1 will now be free for allocation. I'd given an answer for a simple case, like when you have a small main program containing the entire code which was posted in the question.

Cheers :-)

Mayank.
bugsbunny1:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
Recommendation: Split points between mayankeagle and oferh.