"Mohammad Omer" <mo******@gmail.comwrote in message
news:11**********************@o5g2000hsb.googlegro ups.com...
>I am using vs2k5 for C++ IDE. I need to understand concept of the
following Code behavior on VC compiler.
Code-1
---
Object getObject()
{
return Object();
}
<In main function>
Object obj;
Obj = getObject();
This makes a copy of the entire object into main's local variable, ok.
>
Code-2
---
char * getTestArray()
{
char str[256];
strcpy(str, "this Text");
return str;
}
<In main function>
char text[256];
strcpy(text, getTestArray());
This copies a pointer to getTestArray's local memory into main's local
memory. The array the pointer points to is no longer available, so your
program will have undefined behavior (read, random bad things will happen,
you could crash, you could overwrite important data, you could format your
hard disk). In this case, because you are only reading from the bad
pointer, and it's pointer to an invalid location on the stack, you will
probably just get nonsense data copied with strcpy. However, since strcpy
terminates based on finding a NUL character, not a buffer size, the garbage
might not have a NUL in the first 256 bytes, in which case strcpy would
overflow the destination array, overwrite strcpy's stack frame including the
return address, and your program will crash. memcpy, being controlled by
buffer length, wouldn't be so bad -- you'd get a controlled amount of
garbage and no stack corruption -- but the fundamental problem of returning
a pointer to a variable that goes out of scope needs to be corrected.
>
I really need answer of the following question,
1. What is the difference in code-1 and code-2 returning?
2. Will "strcpy(text, getTestArray());" statement make some problem in
feature??
Regards,
-aims