Search code examples
c++access-violationchar-pointer

Why am I getting this access violation?


I'm probably doing something stupid here, but it's been a while since I've worked in C++ and for some reason I keep getting an access violation when sprintf is called. Anyways, here's the code I'm using:

char *value, *result;
int len;
result = "";
mgr.GetObjValue(0, value, len);

for (int i = 0; i < len; i++) 
{
  sprintf(result, "%s %X", result, value[i]);
}

printf("ObjVal: %s\n\n", result);

if anyone is curious what GetObjValue does, it just retrieves the SNMP object value from the API I am using. Here's it's declaration:

int SNMPMgr::GetObjValue(int iObjIndex, char *&lpObjValue, int &lenObjValue);

Any help would be much appreciated


Solution

  • sprintf doesn't do memory allocation. It expects to be given a pointer to a writable buffer of sufficient length to hold the data.

    char *result;
    

    At this point, result's contents are undefined.

    result = "";
    

    At this point, result points to a static, read-only string of 1 byte (the terminating null).

    sprintf(result, "%s %X", result, value[i]);
    

    At this point, you just tried to write an arbitrarily long string to a read-only area of size 1. Oops.

    Do something like this instead:

    char result[1024];
    sprintf(result, "%s %X", result, value[i]);
    

    Note that using snprintf or sprintf_s, to avoid even the possibility of overwriting your buffer, is probably a good idea. (Since you're using C++, you could also easily use one of the C++ formatting libraries, like Boost.Format, that does memory allocation for you - but that's a whole other topic.)