very basic c++: seg fault when doing cross class pointer assignment with malloc
In the following code, 'buf' is malloced, but then why accessing its member gives seg fault?
clas开发者_Python百科s 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.
精彩评论