简体   繁体   中英

strange behavior on c++ string append

I have a strange problem with c++ string object in my class on the 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;
        for (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 with the 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;
    for (i=0; i<s.size(); i++) {
        printf("%c\n", s.c_str()[i]);
    } 
    return 0;
}

But in my project, the line s.append(ptr2str + pOffsets[2 * id], len); seems to corrupt the first byte to be \\x00, according to the debug statement printf(..) before s.append and the cout ... afterwards.

Any idea what caused the strange behavior? Thanks!

UPDATE 1

Thanks to @user657267's suggestion, here is a brief description on how the code was used in my project. It looks very innocent.

cRegexMatches globalVar;

//p points to some c string 
//pInt points to an array of integers, in my case, it's 0,  16, 0, 16
globalVar.update(p, pInt);
cout << globalVar[0]

For now, I found a workaround: I changed the line s.append(ptr2str + pOffsets[2 * id], len); to return string(ptr2str + pOffsets[2 * id], len); and it worked fine. But I am still curious on what caused the strange behavior.

I believe that the problem might be your definition of the string in main.

char* p = "10.20.0.111:8080";

should be

char p[] = "10.20.0.111:8080";

Only the second definition reserves memory on the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM