我必须确保作为参数传递的字符串不会导致溢出。我这样做是通过使用strncpy,但结尾'\ 0',分配适量的内存等等给了我一些麻烦......
我的解决方案是:
l = strlen(argv[optind]);
if(l<MAX_LENGTH) {
msg = malloc((l+1) * sizeof(char));
msg = strcpy(msg, argv[optind]);
} else {
msg = malloc((MAX_LENGTH+1) * sizeof(char));
msg = strncpy(msg, argv[optind], MAX_LENGTH);
msg[MAX_LENGTH+1] = '\0';
}
它有效,但我想知道它是否真的正确,是否有更紧凑的解决方案?
答案 0 :(得分:2)
我认为这是最简单的:
size_t l;
char* msg;
...
l = strlen(argv[optind]);
if (l > MAX_LENGTH) l = MAX_LENGTH;
msg = malloc(l + 1);
if (msg == NULL) /* handle the error as appropriate*/;
memcpy(msg, argv[optind], l);
msg[l] = '\0';
答案 1 :(得分:1)
你可以用以下代码替换所有这些代码:
msg = strdup(argv[optind]);
来自strdup(3)
:
The strdup() function returns a pointer to a new string which
is a duplicate of the string s. Memory for the new string is
obtained with malloc(3), and can be freed with free(3).
The strndup() function is similar, but only copies at most n
characters. If s is longer than n, only n characters are
copied, and a terminating null byte ('\0') is added.
<强>更新强>
CONFORMING TO
strdup() conforms to SVr4, 4.3BSD, POSIX.1-2001. strndup(),
strdupa(), and strndupa() are GNU extensions.
答案 2 :(得分:1)
l = strlen(argv[optind]);
if ( l < MAX_LENGTH) {
msg = malloc(l+1);
if (msg) strcpy(msg, argv[optind]);
} else {
msg = malloc(MAX_LENGTH+1);
if (msg) {
#if 1
memcpy(msg, argv[optind], MAX_LENGTH);
#else
strncpy(msg, argv[optind], MAX_LENGTH);
#endif
msg[MAX_LENGTH] = '\0';
}
}