...
| Code Block | ||
|---|---|---|
| ||
#include <stdio.h>
struct X { char a[6]; };
struct X addressee(void) {
struct X result = { "world" };
return result;
}
int main(void) {
printf("Hello, %s!\n", addressee().a);
return 0;
}
|
This solution is problematic because of three inherent properties of C:
1. In C, the lifetime of a return value ends at the next sequence point. Therefore at by the time printf() is called, the struct returned by the addressee() call might is no longer considered valid, and may have been overwritten.
1. C function arguments are passed by value. Thus, copies are made of all objects generated by the arguments. For example, a copy is made of the pointer to "Hello, %s!\n". Under most circumstances, these copies protect one from the effects of sequence points described above.
1. Finally, C implicitly converts arrays to pointers when passing them as function arguments. This means that in the previous point, a copy is made of the pointer to the addresee().a array, and that pointer copy is passed to printf(). But the array data itself is not copied, and no longer exists when printf() is called.
Before being overwritten, the .a array was converted to a pointer and passed as an argument to printf(). Therefore when printf() tries to dereference the pointer passed as its 2nd argument, it will likely find garbage.
...