非常基本的c ++:在使用malloc进行跨类指针赋值时出现seg错误

luk*_*mac 2 c++

在下面的代码中,'buf'是malloced,但是为什么访问它的成员会给出seg错误?

编辑:感谢cnicutar和大卫,我现在明白了这个问题.

class tool{
   ...
   void do(char* buf){
        buf = malloc(100);
        ... //init buf[0], buf[1], etc
   }
};

class user{
   ...
   tool  *tl;
   char  *buf;

   user(){

       tl = new tool;
       tl -> do(buf);

       cout<<buf[1]<<endl;  //---> gives seg fault!  Why?
   }
};
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 9

你没有写入bufin 的副本user.您所做的就是分配内存,将其存储到本地变量中do(),然后在do()返回时将其忘记.

你需要do()收到一个char**.只有这样做才能do()将新分配的内存返回给调用者.

void _do(char** buf){
    *buf = (char*)malloc(100);
    ... //init buf[0], buf[1], etc
}
...
tl -> _do(&buf);
Run Code Online (Sandbox Code Playgroud)

当然,因为这是C++,我想知道为什么你不使用引用std::string,但也许这是说明性的代码.

  • 或者,通过引用传递指针:`void do(char*&buf){buf =(char*)malloc(100); }` (3认同)
  • @lukmac:您可以考虑使用`std :: vector <char>`来节省自己管理内存(这很容易出错).您可以轻松地获得与其内容的C兼容指针:`&vector [0]`(或C++ 11中的`vector.data()`). (2认同)