-1

why the variable was reset after if statements

print the following message:

recv len1: 122

recv len2: 0

R *r;

void on_recv(struct bufferevent *bev, void *arg)
{
    struct evbuffer *src;
    size_t len;

    src = bufferevent_get_input(bev);
    len = evbuffer_get_length(src);
    ......

    BaseHandler *handler = r->get_handler();
    char data[MAX_BUFSIZE] = { 0 };
    char new_data[MAX_BUFSIZE] = { 0 };
    evbuffer_copyout(src, data, len);
    LOGE("recv len1: %d\n", len);
    if (handler->handle(data, new_data)) {
        LOGE("recv len2: %d\n", len);
    }

    ......

}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Aero Kang
  • 61
  • 4
  • 3
    _why the variable was reset after if statements_ Which variable? Please, elaborate your question. A [mcve] would be appreciated as well. – Scheff's Cat Feb 13 '19 at 08:48
  • 2
    If you're programming in C++, then please leave the C tag out of it. C++ and C are two very different languages. – Some programmer dude Feb 13 '19 at 08:49
  • 2
    *"why the variable was reset"* Without seeing the rest of your program, who knows? Perhaps `handler->handle` invokes some UB that messes with the stack and changes `len` that way. Or maybe `LOGE` is a macro that assigns to `len`. Or it is misleading in other ways, doesn't actually print `len` and maintains some state elsewhere to cause the different results. – Blaze Feb 13 '19 at 08:50
  • 1
    If it's about `len` - this smells like [Undefined Behavior](https://stackoverflow.com/a/4105123/1505939). I would carefully watch for out of range accesses. – Scheff's Cat Feb 13 '19 at 08:50
  • You should consider running a debug-build of your program in a memory debugger tool (like e.g. [Valgrind](http://valgrind.org/)). That should help you find possible out-of-bounds writes as well as other possible problems. – Some programmer dude Feb 13 '19 at 08:52
  • The problem is most likely in the `handle` method. You should show us at least this method. You can [edit] your question. – Jabberwocky Feb 13 '19 at 08:55
  • 3
    Do not write pseudocode examples, defect is in your actual code, and not where you imagine it is. – Öö Tiib Feb 13 '19 at 08:55

1 Answers1

0

This looks like a buffer-overflow: You are writing past the end of either data or new_data and so you are overwriting len with NUL bytes apparently.

Solution: Pass the actual buffer sizes to function handle() and make sure this does not access (read and write) beyond the end of the passed arrays.

You can also print handler before and within the if(). This should also get corrupted as it is between len and the arrays.

Johannes Overmann
  • 4,914
  • 22
  • 38