【问题标题】:Why does this sprintf_s throw an exception?为什么这个 sprintf_s 会抛出异常?
【发布时间】:2021-11-24 16:09:40
【问题描述】:
char filePrefix[] = "test";
char fileName[100]; fileName[0] = 0;
sprintf_s(fileName, "%s", filePrefix);

我不知道为什么在 sprintf_s 中写入 fileName 时出现异常

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

【问题讨论】:

  • 阅读文档。您在 fileName 之后缺少 buffersize 参数。
  • 顺便说一句,没有必要使用这个微软特有的功能。有一个类似的标准snprintf()
  • 那是sprintf,不是sprintf_s
  • @FredLarson 它是可选实现的一部分,详见规范的附件K。
  • @FredLarson 进一步阅读附件:stackoverflow.com/questions/372980/…

标签: c visual-studio-2019 tr24731


【解决方案1】:

documentation 开始,sprintf_s 的第二个参数应该是目标缓冲区的大小。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2010-11-06
    • 2015-05-23
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多