gpt4 book ai didi

c - 使用 snprintf 避免缓冲区溢出

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:32 25 4
gpt4 key购买 nike

I dont understand why I am getting an output like this: StackOver↨< as snprintf should take care of null termination as expected output is StackOver. I am using devcpp IDE.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{
char buffer[10];
printf("%d\n", sizeof(buffer));
snprintf(buffer, sizeof(buffer), "%s", "StackOverflow");
printf("%s", buffer);
return 0;
}

最佳答案

C Standard states复制的字符串应以 nul 结尾:

7.21.6.5 The snprintf function

...

Description

The snprintf function is equivalent to fprintf , except that the output is written into an array (specified by argument s ) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.

看来您正在使用过时的和/或错误的 C 运行时库运行,因为 snprintf() 实现似乎没有正确实现所需的行为。

关于c - 使用 snprintf 避免缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41534912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com