In the following code, 'buf' is malloced, but then why accessing its member gives seg fault?
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?
}
};
You didn't write to the copy of buf in user. All you did was allocate the memory, store it to a local variable in do() and then forget about it when do() returned.
You need do() to receive a char**. Only if you do it this way can do() return the newly allocated memory to the caller.
void _do(char** buf){
*buf = (char*)malloc(100);
... //init buf[0], buf[1], etc
}
...
tl -> _do(&buf);
Of course, since this is C++ I wonder why you don't use references and std::string, but perhaps this is illustrative code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With