(cxx) std::string转char *的问题

软件和网站开发以及相关技术探讨
回复
tusooa
帖子: 6548
注册时间: 2008-10-31 22:12
系统: 践兔
联系:

(cxx) std::string转char *的问题

#1

帖子 tusooa » 2009-08-29 16:13

代码: 全选

>> 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;
}
>>
ps:
>> 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
怎么回事?

代码: 全选

] ls -ld //
头像
bones7456
帖子: 8495
注册时间: 2006-04-12 20:05
来自: 杭州
联系:

Re: (cxx) std::string转char *的问题

#2

帖子 bones7456 » 2009-08-29 16:37

char *str; 只是声明了一个指针,还没申请空间,就往里面塞东西,不段错误才怪。
关注我的blog: ε==3
头像
tianyaqu
帖子: 97
注册时间: 2008-12-05 20:43
来自: 深圳

Re: (cxx) std::string转char *的问题

#3

帖子 tianyaqu » 2009-08-29 16:56

:em04 char str[10];。。。我也曾这么写过。。。
道是何物,直教,生死相许?
回复