【发布时间】:2011-12-25 03:31:10
【问题描述】:
我正在制作的较大程序的一部分需要从命令行读取路径并存储在类中。因为路径可以是任意大小并且在多个函数中都需要它,所以我将它存储在头文件中的 char* 中。但是,由于某种原因,当我为其赋值时,程序会出现段错误。
调试器 (gdb) 显示如下:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b4828a in std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char> >(std::basic_istream<char, std::char_traits<char> >&, char*) ()
from /usr/lib/libstdc++.so.6
这是我为演示问题而编写的程序:
test.cpp:
#include "test.h"
#include <iostream>
#include <cstring>
Test::Test() {
filepath = NULL;
}
void Test::set_path(char* string) {
char temp[strlen(string) + 1];
strcpy(filepath, temp);
}
char * Test::get_path() {
return filepath;
}
int main(int argc, char *argv[]) {
std::cout << "Enter a file path: ";
char *temp;
std::cin >> temp;
Test *temp2 = new Test();
temp2->set_path(temp);
std::cout << "Path: " << temp2->get_path() << std::endl;
}
test.h:
#ifndef TEST_H
#define TEST_H
class Test {
private:
char *filepath;
public:
Test();
void set_path(char *);
char * get_path();
};
#endif // TEST_H
我不确定它为什么会崩溃。我这样做的方法有问题吗?另外,我不只是切换到strings,还想了解更多关于这个问题的信息。
提前致谢!
【问题讨论】:
-
"而不是仅仅切换到
strings,我想了解更多关于这个问题的信息。"为什么,你对strings 过敏? -
我确实最终使用了
std::string'。我只是想弄清楚为什么char *不起作用。