Home > Blockchain >  buffer overrun while trying to link two strings together, why do I have this error?
buffer overrun while trying to link two strings together, why do I have this error?

Time:11-18

(in C, using visual studio 2022 preview), I have to do a program that link two strings together. Here's what I did:

  1. I wrote two for-loops to count characters of first string and second string,

  2. I checked (inside the link function if the pointers are null (first and second). If they are null, then "return NULL".

  3. I created "char *result". this is a new string and this is the string to be returned. I allocated enough memory to store nprime, nsecond, and 1 more character (the zero terminator). I used a malloc.

  4. then, I checked if result is null. if it's null then "return NULL".

  5. then, I wrote 2 for-loops to perform the linking between the first string and the second string. And here I got a compiler warning (because I think it's in compile time not in debug time). buffer overrun, the writable size is "nprime nsecond 1" but 2 bytes might be written. my theory is that the program is trying to write outside the result-array, so there could be a loss of data, I tried to edit my code, therefore I write "nprime nsecond 2" instead but it doesn't work, and it keeps showing me the same buffer overrun error.

    #include <stdlib.h> 
    
    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; 
    }
    

this is the main:

int main(void) {
char s1[] = "this is a general string  "; 
char s2[] = "this is a general test."; 
char* s; 
    
s = link(s1, s2); 
return 0; 
}

CodePudding user response:

The warning is given due to the wrong conditions you defined in the first 2 for loops. The right loops should be as follows:

for (size_t i = 0; first[i] != '\0'; i  ) {
    nprime  ; 
}
for (size_t i = 0; second[i] != '\0'; i  ) {
    nsecond  ; 
}

With the conditions you defined (i.e. first[i] < '\0') you are just counting how many chars in the given string have an ASCII code lower than the ASCII code of \0 and exit the loop as soon as you find a char not fulfilling such condition.

Since '\0' has ASCII value 0, your nprime and nsecond are never incremented, leading to a malloc with insufficient room for the chars you actually need.

  • Related