strange behavior on c++ string append -


i have strange problem c++ string object in class on line s.append(ptr2str ....);

class cregexmatches { public:     char *ptr2str;     int   *poffsets;     cregexmatches() { ptr2str = null; poffsets=null;}     void update(char *p, int *offsets) {         ptr2str = p; poffsets = offsets;         printf("ptr2str=%p %s|\n", p, p);     }     string operator [] (int id) {         string s;         printf("operator[] %p %s|", ptr2str, ptr2str);         int i;         (i=0; i<4; i++) printf(" %d", poffsets[i]);         printf("\n");         if (!ptr2str) return s;         if (poffsets[2 * id + 1] == 0) return s;         int len = poffsets[2 * id + 1] - poffsets[2 * id];         printf("size %d %ld before %s\n", s.size(), len, ptr2str + poffsets[2 * id]);         s.append(ptr2str + poffsets[2 * id], len);         cout << s << endl;         return s;     } }; 

it runs fine follow code.

int main(int argc, char *argv[]) {     char *p = "10.20.0.111:8080";     int pints[] = {0, 16, 0,16};     regmatches.update(p, &pints[0]);     string s =  regmatches[0];     int i;     (i=0; i<s.size(); i++) {         printf("%c\n", s.c_str()[i]);     }      return 0; } 

but in project, line s.append(ptr2str + poffsets[2 * id], len); seems corrupt first byte \x00, according debug statement printf(..) before s.append , cout ... afterwards.

any idea caused strange behavior? thanks!

update 1

thanks @user657267's suggestion, here brief description on how code used in project. looks innocent.

cregexmatches globalvar;  //p points c string  //pint points array of integers, in case, it's 0,  16, 0, 16 globalvar.update(p, pint); cout << globalvar[0] 

for now, found workaround: changed line s.append(ptr2str + poffsets[2 * id], len); return string(ptr2str + poffsets[2 * id], len); , worked fine. still curious on caused strange behavior.

i believe problem might definition of string in main.

char* p = "10.20.0.111:8080"; 

should be

char p[] = "10.20.0.111:8080"; 

only second definition reserves memory on stack.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -