0

I have simple code:

#define NUM_UA_SOCK     100

typedef struct _UA_REQUEST
{
    string full_url;
    uint32_t        url_adler32 ;
    TCPsocket   sock_ua ;
    uint32_t    status_flag ;               // ref Enum STATUS
} UA_REQUEST ;

UA_REQUEST  GLB_ARRAY__UA_REQ[ NUM_UA_SOCK ] ;

void handle_ua_sock_ready( uint32_t ii )
{
    string _req_mstr;

    byte*request    = (byte*) _req_mstr.c_str() ;
    byte*pcrlf  = NULL ;

    UA_REQUEST*ar = GLB_ARRAY__UA_REQ ;

    // Get request from UA
    int32_t nrcv ;

    printf("index =  %lu\n", ii);
    TCPsocket sock = ar[ii].sock_ua;
    nrcv = SDLNet_TCP_Recv( sock , request , MAXLEN ) ;
    printf("After index =  %lu\n", ii);
}

The ii variable in begin of handle_ua_sock_ready() func has the 0 value. After invoking nrcv = SDLNet_TCP_Recv( sock , request , MAXLEN ) ; line it becomes to have something very big value for instance 1852397344. It is single-threaded app. I'm using VS 2010, SDL, SDL_net libraries. PS: When I compiled it under Linux, it works fine.

genpfault
  • 51,148
  • 11
  • 85
  • 139
Slava
  • 53
  • 1
  • 5
  • 1
    You code is incomplete (`request`, `ar`, `MAXLEN` declarations) but you are likely to have a buffer overflow in a stack object. – ouah Jun 15 '15 at 12:37
  • 5
    Don't use symbols with leading underscore followed by a capical letter, those are reserved in all scopes. [See here for more information.](http://stackoverflow.com/a/228797/440558) – Some programmer dude Jun 15 '15 at 12:38
  • 4
    Also, you probably have undefined behavior in your code. The data returned by [`c_str`](http://en.cppreference.com/w/cpp/string/basic_string/c_str) is *read only*, attempting to write to this array leads to undefined behavior. Also, if the length of the string is less than `MAXLEN` you might even be writing out of bounds, once again leading to UB. – Some programmer dude Jun 15 '15 at 12:41
  • when #define'ing numeric values, surround the numeric value with parens '(' ')' to avoid any 'text substitution' errors – user3629249 Jun 15 '15 at 12:45
  • this is 'c++' code, please remove the 'c' tag – user3629249 Jun 15 '15 at 12:49

1 Answers1

0

You're passing in request to the SDLNet_TCP_Recv function and telling that function that request points to a buffer of size MAXLEN. As request comes from casting away the constness from the buffer of an empty std::string this is clearly wrong.

You want a vector

std::vector<unsigned char> request;
request.resize(MAXLEN);

...

nrcv = SDLNet_TCP_Recv( sock , request.data() , request.size() ) ;
Mike Vine
  • 9,468
  • 25
  • 44