C question from an interview
In What lines will this code fail (meaning: don't do what they are supposed to do), and why?
int main(void) {
char student[64] = "some guy";
char* teacher;
开发者_如何转开发
/* line1 */ strcpy(teacher, student);
/* line2 */ teacher=student;
/* line3 */ strcpy(student, "Alber Einstein");
/* line4 */ student = teacher;
}
Line 1 causes undefined behaviour. Line 4 won't even compile. Since this seems like it could just as easily be a homework question, and I don't like to give the whole thing away, a quick read of the comp.lang.c FAQ or the C language specification will explain why.
Sort of in jest, but also serious:
Line 1 fails because you used the
strcpy( )
function, which may result in the copy overwriting the bounds of the destination buffer if a maintenance programmer increases the size of thestudent
array at some point in the future. This could potentially allow arbitrary code execution in some environments, and is a security vulnerability.Line 2 fails because you now have two names for the same block of memory, which may result in aliasing conflicts and data corruption if both are used later.
Line 3 fails because you have spelled Albert Einstein's name incorrectly.
Line 4 fails because it's invalid C.
The point is, you need to have a spec before you can have a meaningful discussion about how a program does or does not fail.
strcpy(teacher, student);
This fails because you have not allocated memory using malloc()
to the teacher. It points to random, and will write to random. UB
is on the way
In addition to what others have said:
If you're using a C89 compiler, line 5 "fails" (*)
The function main
is special only in that it is the function called by the implementation at program startup. Unlike for C99, it is not special in how it terminates. A function with a return type different than void
MUST (in C89 and, except for main
, in C99) return something to avoid undefined behaviour.
(*) in C99 there is an implicit return 0;
right before the closing brace of the function main
The compiler will complain at /* line 4 */. By declaring student in that manner, student will behave like a constant pointer to the starting address of a 64-byte block. It can't be assigned to, though it can be referenced (in lines 1 + 2) and have the memory it points to altered (in line 3).
line 4 will definitely fail, since the declaration char student[64]
essentially defines student
to be a constant pointer to a character. The assigment attempts to change the value of the pointer (not the string to which it points), which would violate its constant nature.
line 1 should cause problems at run-time, but will pass the compiler (maybe have a warning generated). Since teach has not been assigned anything (i.e. it is an invalid pointer), you can't copy a value into the location to which it points, since it doesn't really point to anywhere.
精彩评论