Saturday, 15 May 2010

c++ - Problems keeping objects alive -



c++ - Problems keeping objects alive -

i've encountered weird problem doesn't create sense me.

i've struct (that contains string) on api defined follows:

typedef struct sncharcb { char * pdata; int idatalen; } tsncharcb;

i need save deep re-create of struct. have created utility function create re-create of struct:

inline sncharcb rapi_strcpy(const sncharcb &rapistr) { sncharcb res; res.pdata = new char[rapistr.idatalen]; strcpy(res.pdata, rapistr.pdata); res.idatalen = rapistr.idatalen; homecoming res; }

i create copies of "sncharcb" structs using utility method , save them reference variables in parent object:

stored_sncharcb = rapi_strcpy(sncharcb_to_copy);

after short while these stored values magically changed contain random garbage. parent object these values stored within scope time , it's not destructed. might causing these values wiped prematurely?

is info in pdata null terminated? if not, strcpy phone call in rapi_strcpy may running off end , hence copying beyond size allocated in target.

you want using forces length, strncpy or memcpy:

strncpy(res->pdata, rapistr.pdata, rapistr.idatalen);

c++

No comments:

Post a Comment