- 论坛徽章:
- 0
|
- #include <stdio.h>
- #define MAXLINE 10
- int getline1(char line[], int maxline);
- int main() {
- int len;
- char line[MAXLINE];
- len = getline1(line, MAXLINE);
- while (len > 0) {
- printf("main:%d\n", len);
- len = getline1(line, MAXLINE);
- }
-
- return 0;
- }
- int getline1(char line[], int maxline) {
- int len = 0;
- int j = 0;
- int c;
- for (; (c = getchar()) != EOF && c!='\n'; ++len) {
- line[len] = c; [color=Red] //应该是这里导致了 stack smashing detected[/color]
- if (len < maxline - 2) {
- line[j] = c;
- ++j;
- }
- }
- if (c == '\n') {
- line[j] = c;
- j++;
- len++;
- }
- line[j] = '\0';
- return len;
- }
复制代码 运行的的结果:- bells@bells-VirtualBox ~/Desktop/c2/1 $ ./a.out < text.txt
- main:20
- main:10
- main:3
- *** stack smashing detected ***: ./a.out terminated
- Aborted
- bells@bells-VirtualBox ~/Desktop/c2/1 $
复制代码 其中text.txt 的内容:- bells@bells-VirtualBox ~/Desktop/c2/1 $ cat text.txt
- jldjals;jfl;asjf;la
- zxcvbnmjk
- we
- bells@bells-VirtualBox ~/Desktop/c2/1 $
复制代码 用gdb调试了好久,不明白为什么stack smashing detected
把for循环里的“line[len] = c;”这句去掉,就木有了。但是我觉得加上也木有关系的。
而却stack smashing detected 是在main函数里,都已经return 0之后,抛出的,请看:- ...
- Breakpoint 2, main () at exercise17.c:12
- 12 printf("main:%d\n", len);
- (gdb) c
- Continuing.
- main:3
- Breakpoint 1, main () at exercise17.c:13
- 13 len = getline1(line, MAXLINE);
- (gdb) n
- 11 while (len > 0) {
- (gdb) print len
- $1 = 0
- (gdb) n
- 16 return 0; [color=Red]//这里都已经执行完了[/color]
- (gdb) n
- 17 }
- (gdb) n
- *** stack smashing detected ***: /home/bells/Desktop/c2/1/a.out terminated [color=Red]//这里为什么呢?[/color]
- Program received signal SIGABRT, Aborted.
- 0xb7fdd416 in __kernel_vsyscall ()
- (gdb)
复制代码 请各位大侠指点下!! |
|