代码: 全选
>> vim main.cc
>> c++ main.cc
>> ls
a.out main.cc
>> ./a.out
段错误
>> cat main.cc
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string cmdstr = "...";
char *str;
strcpy(str, cmdstr.c_str());
cout << str << endl;
return 0;
}
>>
怎么回事?>> c++ main.cc -g
>> gdb ./a.out
GNU gdb 6.8-debian
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu"...
(gdb) l
1 #include <cstring>
2 #include <string>
3 #include <iostream>
4 using namespace std;
5
6 int main(int argc, char *argv[])
7 {
8 string cmdstr = "...";
9 char *str;
10 strcpy(str, cmdstr.c_str());
(gdb)
11 cout << str << endl;
12 return 0;
13 }
14
(gdb)
Line number 15 out of range; main.cc has 14 lines.
(gdb) b 9
Breakpoint 1 at 0x400ba4: file main.cc, line 9.
(gdb) b 11
Breakpoint 2 at 0x400bb9: file main.cc, line 11.
(gdb) b 10
Note: breakpoint 1 also set at pc 0x400ba4.
Breakpoint 3 at 0x400ba4: file main.cc, line 10.
(gdb) r
Starting program: /home/tusooa/develop/cxx_tests/a.out
Breakpoint 1, main (argc=1, argv=0x7fff267656e8) at main.cc:10
10 strcpy(str, cmdstr.c_str());
(gdb) c
Continuing.
Program received signal SIGSEGV, Segmentation fault.
0x00007fd51daac7a0 in strcpy () from /lib/libc.so.6
(gdb) quit
The program is running. Exit anyway? (y or n) y