flawfinder-2错误溢出缓冲区(字符,strlen)

问题描述 投票:-1回答:1

我试图弄清楚如何在程序中解决2个匹配,但我不明白如何...

我有这段代码:

#include <stdio.h>
#include <string.h>
#define MAXSIZE     40
void test(char *str) {
    char buf[MAXSIZE];
    if(strlen(str) > MAXSIZE)
        return;
    strlcpy(buf, str);               
    printf("result: %s\n", buf);
}

int main(int argc, char **argv) {
    char *userstr;

    if(argc > 1) {
        userstr = argv[1];
        test(userstr);
    }
    int i[10];
    int j = 0;

    while (j < 10000)
    {
        i[j] = 5;                
        ++j;
    }

    for (j = 0; j < sizeof i / sizeof i[0]; ++j)
        printf("Value = %d\n", i[j]);
    return 0;
}

我得到了这2个热门歌曲:

C:\Users\vord\codetest\test1.txt:5:  [2] (buffer) char:
  Statically-sized arrays can be improperly restricted, leading to potential
  overflows or other issues (CWE-119!/CWE-120). Perform bounds checking, use
  functions that limit length, or ensure that the size is larger than the
  maximum possible length.
C:\Users\vord\codetest\test1.txt:6:  [1] (buffer) strlen:
  Does not handle strings that are not \0-terminated; if given one it may
  perform an over-read (it could cause a crash if unprotected) (CWE-126).

我试图理解的第一击,因为MAXSIZE已经设置为40,所以已经受到限制...我搜索了第二个解决方案,但发现不起作用...

[如果您能帮助我找出解决这些问题的方法,我将非常高兴。

c security
1个回答
0
投票

strlen()函数返回不计算结尾'\ 0'的字符串长度,因此您需要声明大小等于MAXSIZE + 1的缓冲区。另外,为确保buf被零终止(printf()调用需要什么),只需将buf初始化为0。在这种情况下,这是最便宜的解决方案。

尝试一下:

© www.soinside.com 2019 - 2024. All rights reserved.