1

I have a c++ application, in which customer reported a crash.But the crash is not easily reproducible. After analysing some logs and all i found that the crash may occure in between the following code portions. Please tell me there is any chance of getting crashed the application if i have these code statements in it?

    //Tesrt
    std::string strAppName = "App1\0";
    int nSize = 10;
    sprintf_s(szBuff, "The appname %s have %d dependancies ", strAppName.c_str(), nSize);
    //Then use the szBuff to log to a text file
    //Test end
5
  • The null character in the literal assigned to strAppName is redundant. Commented Jun 29, 2012 at 11:27
  • @nhahtdh: I think you are confusing sprintf_s with sprintf. Also, assuming an int to be 32-bit is not very portable. Commented Jun 29, 2012 at 11:27
  • @NiklasB.: OK. I got the point, since this is the safe version from Windows. About int, I'm not sure if there is any implementation with 64-bit, though (according to Wikipedia). Commented Jun 29, 2012 at 11:35
  • sprintf_s either takes a char array by reference OR a pointer to char and a size parameter. Commented Jun 29, 2012 at 11:39
  • @Charles: Yeah, my mistake. I didn't look close enough. Commented Jun 29, 2012 at 11:39

1 Answer 1

2

The problem is that you've not provided the correct arguments to sprintf_s:

int sprintf_s(
   char *buffer,
   size_t sizeOfBuffer,
   const char *format [,
      argument] ... 
);

sprintf_s takes a size_t as it's second argument (the size of szBuff), but you've not provided that. Instead, you've given it a const char * where that parameter should be. The only way to have compiled this is for you to have ignored compiler warnings.

So what sprintf_s is seeing is: buffer to print into large number of characters allowed to go into buffer strAppName.c_str() as the format string

In other words, this isn't doing anything like what you want. Provide the size of szBuff as the second parameter, and I'll bet your problems go away.

And yes, given what you've done I'd expect crashes all over the place.

Sign up to request clarification or add additional context in comments.

4 Comments

szBuff is declared as follows char szBuff[1024];
Unless szBuff really is an array and he is using the template version. (Aside: how someone can develop a template overload where the parameters shift around in such a dangerous way and still use _s as a suffix, I don't know.)
@Charles: Wow, didn't even see that. Really bad design. Sorry, Minnu, maybe I was wrong there.
Ok, but i have another code portion as follows "sprintf_s(szBuff, "Handle %d has %d items ",nSize,nItemSize) ie, with fixed integer arguments ..is it become problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.