有没有办法防止C中的缓冲区溢出? 如果我无法确定字符串长度,我怎么知道何时停止?
x = malloc(strlen(unsafe_string) + 1);
memcpy(x, unsafe_string, strlen(unsafe_string) + 1);
答案 0 :(得分: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
这里。