0

I meet problem. Example:

try
{
    char strMes[6];
    sprintf_s(strMes, sizeof(strMes), "%s", "012345678");
    printf(strMes);
}
catch(...)
{
    printf("Wrong\n");
}

In debug environment it caused for debugger "buffer too small" message.

In release environment it caused for crash.

I tried to replace try-catch block to __try-__except(EXCEPTION_EXECUTE_HANDLER) block, but I get the same behavior.

I have about 1K callings for sprintf_s function, so replace sprintf_s to _snprintf_s is not option for me. (see sprintf_s with a buffer too small)

Please help!

Community
  • 1
  • 1
Vlad
  • 1
  • 1
  • 1
  • What were you expecting? you are trying to write past the end of a buffer, either limit your write to the size of the buffer (which in your case you can do in a decent editor with a simple search/replace) or enlarge the buffer. – Hasturkun Aug 07 '11 at 11:32
  • Make the buffer(s) bigger / Replace `sprintf_s` with `_snprintf` which takes the same parameters. – user786653 Aug 07 '11 at 11:32

4 Answers4

5

First of all, I believe you should use snprintf instead of sprintf_s.

Second, there is an invalid paramater handler for CRT that gets called. Try setting that.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
1

You must check the return value of sprintf_s before using strMes any further. Otherwise how do you know whether the buffer was big enough? sprinft_s may have nothing written to strMes and so it is still uninitialized. That's what's causing the crash (try removing the sprintf_s, it likely crashes as well.)

From the sprintf_s docs:

The number of characters written, or –1 if an error occurred. If buffer or format is a null pointer, sprintf_s and swprintf_s return -1 and set errno to EINVAL.

PS: You should tag this question C++ not C due to try/catch.

Jens
  • 69,818
  • 15
  • 125
  • 179
1

Read the documentation:

.... If either check fails, the invalid parameter handler is invoked, as described in Parameter Validation ...

The default behaviour is throwing. You can override it.

J-16 SDiZ
  • 26,473
  • 4
  • 65
  • 84
0

If your VS version supports, you should run Code Analysis on it.

Read about About Code Analysis

Ajay
  • 18,086
  • 12
  • 59
  • 105