Discussion:
Why does this crash?
(too old to reply)
Vincent Fatica
2010-06-01 17:18:45 UTC
Permalink
#include <windows.h>
#include <stdio.h>

INT wmain ( INT argc, WCHAR **argv )
{
WCHAR szFile[MAX_PATH] = L"\"";

wsprintf(szFile + 1 + GetTempPath(MAX_PATH, szFile + 1), L"foobar.txt\"");

wprintf(L"%s\n", szFile);

return 0;
}

When I build the above (/MT, /MTd, VC9) it prints the correct string and then
crashes. The debug version attributes the crash to stack corruption near
szFile. What's up with that? Thanks.
--
- Vince
Vincent Fatica
2010-06-01 17:38:33 UTC
Permalink
On 1 Jun 2010 13:18:45 -0400, Vincent Fatica <***@blackholespam.net> wrote:

|#include <windows.h>
|#include <stdio.h>
|
|INT wmain ( INT argc, WCHAR **argv )
|{
| WCHAR szFile[MAX_PATH] = L"\"";
|
| wsprintf(szFile + 1 + GetTempPath(MAX_PATH, szFile + 1), L"foobar.txt\"");
|
| wprintf(L"%s\n", szFile);
|
| return 0;
|}
|
|When I build the above (/MT, /MTd, VC9) it prints the correct string and then
|crashes. The debug version attributes the crash to stack corruption near
|szFile. What's up with that? Thanks.

OK, I get it. That should be

... GetTempPath(MAX_PATH - 1, ...

but I'm a bit surprised. The temp path is short. Do you suppose GetTempPath()
is zeroing the whole buffer? I have been sloppy with buffer sizes before and
never ran into such a problem until today.
--
- Vince
Brian Muth
2010-06-01 18:36:46 UTC
Permalink
Post by Vincent Fatica
OK, I get it. That should be
... GetTempPath(MAX_PATH - 1, ...
but I'm a bit surprised. The temp path is short. Do you suppose GetTempPath()
is zeroing the whole buffer?
Yes. You informed GetTempPath that the buffer size was MAX_PATH, and it was
zeroed.
Post by Vincent Fatica
I have been sloppy with buffer sizes before and
never ran into such a problem until today.
Lesson learned, I trust.
Vincent Fatica
2010-06-01 19:00:25 UTC
Permalink
On Tue, 1 Jun 2010 11:36:46 -0700, "Brian Muth" <***@mvps.org> wrote:

|> OK, I get it. That should be
|>
|> ... GetTempPath(MAX_PATH - 1, ...
|>
|> but I'm a bit surprised. The temp path is short. Do you suppose
|> GetTempPath()
|> is zeroing the whole buffer?
|
|Yes. You informed GetTempPath that the buffer size was MAX_PATH, and it was
|zeroed.
|
|
|> I have been sloppy with buffer sizes before and
|> never ran into such a problem until today.
|
|Lesson learned, I trust.

Yes, indeed! Do you think many similar Win32 functions (put a string in a
buffer of stated size) zero the whole buffer? If they do, I think I'd have
learned this lesson a long time ago.
--
- Vince
Brian Muth
2010-06-01 19:18:36 UTC
Permalink
Post by Vincent Fatica
Yes, indeed! Do you think many similar Win32 functions (put a string in a
buffer of stated size) zero the whole buffer?
I don't know. Probably not, but that's just pure speculation on my part.
Loading...