gpt4 book ai didi

c - 防止C中的缓冲区溢出

转载 作者:行者123 更新时间:2023-11-30 21:03:48 25 4
gpt4 key购买 nike

有什么办法可以防止C语言中的缓冲区溢出吗?如果我无法确定字符串长度,我如何知道何时停止?

x = malloc(strlen(unsafe_string) + 1);
memcpy(x, unsafe_string, strlen(unsafe_string) + 1);

最佳答案

使用strnlen并检查malloc是否成功,如下所示

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

int main(int argc, char *argv[]) {
char *unsafe_string = "hello, world"; /* whatever */

size_t max_len = 1024 * 1024; /* one megabyte */
size_t len = strnlen(unsafe_string, max_len) + 1; /* the smaller of the length,
or 1 mb */
char *x = malloc(len * sizeof(char *)); /* malloc len */
if (x != NULL) { /* check for success */
strncpy(x, unsafe_string, len); /* safe string copy */
x[len+1] = '\0';
puts(x);
free(x);
}
}

仅打印

$ gcc hello.c
$ ./a.out
hello, world

这里。

关于c - 防止C中的缓冲区溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20724944/

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