简体   繁体   中英

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. I've counted the strings. I've dynamically allocated enough memory to store each letter, plus the NULL pointer. 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:

// 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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