Home > front end >  Why does this sprintf_s throw an exception?
Why does this sprintf_s throw an exception?

Time:11-25

char filePrefix[] = "test";
char fileName[100]; fileName[0] = 0;
sprintf_s(fileName, "%s", filePrefix);

I can't figure out why there's an exception writing into fileName in the sprintf_s

Exception thrown at 0x00007FF885E3F3A9 (ucrtbased.dll) in foo.exe: 0xC0000005: Access violation writing location 0x0000008331F00000.

CodePudding user response:

From the documentation, the second argument to sprintf_s should be the size of the destination buffer.

char filePrefix[] = "test";
char fileName[100];
fileName[0] = 0;
sprintf_s(fileName, sizeof fileName, "%s", filePrefix);
  • Related