简体   繁体   English

如何解决 c 程序(像这个)中的缓冲区溢出错误/警告?

[英]how to solve a buffer overrun error/warning in a c program (like this one)?

I have to do a program that link two strings together, here's what I did:我必须做一个将两个字符串链接在一起的程序,这就是我所做的:

I've initialized two variables, and they are supposed to store the length of the strings.我已经初始化了两个变量,它们应该存储字符串的长度。 I've checked for NULL pointer exceptions.我检查了 NULL 指针异常。 I've counted the strings.我数过琴弦。 I've dynamically allocated enough memory to store each letter, plus the NULL pointer.我已经动态分配了足够的 memory 来存储每个字母,以及 NULL 指针。 I've put each character in the result string.我已将每个字符放入结果字符串中。

but there's a buffer overrun issue in these lines:但是这些行中存在缓冲区溢出问题:

for (size_t i = 0; i < nprime; i++) {
        result[i] = first[i];
    } 

it's not the first time I encounter this kind of error/warning, and every time I encounter this warning I don't know how to proceed further to solve it, even if I try to change the variable types from a smaller one to a wider one, the problem persists.这不是我第一次遇到这种错误/警告,每次遇到这种警告我都不知道如何进一步解决它,即使我尝试将变量类型从较小的类型更改为较宽的类型一、问题依旧。

what is your approach when you encounter this kind of error?当你遇到这种错误时,你的方法是什么? what do you do to try to fix it?你会怎么做才能修复它? do you have a checklist?你有清单吗?

this is the minimal reproducible example:这是最小的可重现示例:

char* link( const char* first, const char* second) {
    size_t nprime = 0; 
    size_t nsecond = 0; 

    if (first == NULL) {
        return NULL; 
    }
    if (second == NULL) {
        return NULL; 
    }
    for (size_t i = 0; first[i] != '\0'; i++) {
        nprime++; 
    }
    for (size_t i = 0; second[i] != '\0'; i++) {
        nsecond++; 
    }
    char* result = malloc(nprime + nsecond + 1); 
    if (result == NULL) {
        return NULL; 
    }

    for (size_t i = 0; i < nprime; i++) {
        result[i] = first[i]; 
    }
    for (size_t i = 0; i < nsecond; i++) {
        result[nprime + i] = second[i]; 
    }
    result[nprime + nsecond] = 0; 

    return result; 

To text for potential overflow in size_t addition:size_t中添加可能溢出的文本:

// nprime + nsecond + 1
size_t sum = nprime + nsecond + 1u;  // Unsigned math wraps on overflow

// Check if overflow occurred 
if (sum <= nprime) {
  return NULL;   // length too long
}

// char* result = malloc(nprime + nsecond + 1); 
char* result = malloc(sum); 

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

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