scanf("%3c", &c);
My girlfriend CC asked me a question about C programming language today, “What does
1 2 3 4 5 6 7 8 | # include<stdio.h> int main(){ char c; scanf("%3c", &c); printf("%c\n", c); return 0; } |
Really simple, right? And it passed the compilation perfectly, no errors and no warnings, under
1 2 3 | a *** stack smashing detected ***: <unknown> terminated Aborted (core dumped) |
In conclusion,
I tried to see the neighbors of
1 2 3 4 5 6 7 8 9 | #include <stdio.h> int main(){ char c; scanf("%3c", &c); char *p = &c; printf("%d,%d,%d\n", *(p - 1), *p, *(p + 1)); return 0; } |
Run it, input
1 | 0,97,-81 |
- Where does
-81 come from? - Why no “terminal”?
With the two questions, I reran the code several times with the same steps. Ans I found that the output was always like
1 2 3 4 5 6 7 8 9 | #include <stdio.h> int main(){ char c; scanf("%c", &c); char *p = &c; printf("%d,%d,%d\n", *(p - 1), *p, *(p + 1)); return 0; } |
- Let’s answer the first question. As the memory space behind the pointer
p points was unallocated, its value stayed unsure. When we tried toprintf its value in decimal, we could see the value between-128 and127 , the decimal domain of an 8-bit. - As for the “terminal”, I cannot figure it out. I just created a pointer to
c and the error disappeared. Maybe it just didn’t trigger the protection mechanism used bygcc .