- 論壇徽章:
- 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] //應(yīng)該是這里導(dǎo)致了 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;
- }
復(fù)制代碼 運(yùn)行的的結(jié)果:- 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 $
復(fù)制代碼 其中text.txt 的內(nèi)容:- bells@bells-VirtualBox ~/Desktop/c2/1 $ cat text.txt
- jldjals;jfl;asjf;la
- zxcvbnmjk
- we
- bells@bells-VirtualBox ~/Desktop/c2/1 $
復(fù)制代碼 用gdb調(diào)試了好久,不明白為什么stack smashing detected
把for循環(huán)里的“l(fā)ine[len] = c;”這句去掉,就木有了。但是我覺(jué)得加上也木有關(guān)系的。
而卻stack smashing detected 是在main函數(shù)里,都已經(jīng)return 0之后,拋出的,請(qǐng)看:- ...
- 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]//這里都已經(jīng)執(zhí)行完了[/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)
復(fù)制代碼 請(qǐng)各位大俠指點(diǎn)下!! |
|