繁体   English   中英

确保作为参数传递的字符串不会导致溢出

[英]Make sure a string passed as argument does not cause an overflow

我必须确保作为参数传递的字符串不会导致溢出。 我这样做是通过使用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';
} 

它有效,但我想知道它是否真的正确,是否有更紧凑的解决方案?

我认为这是最简单的:

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';

你可以用以下代码替换所有这些代码:

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.
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';
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM