String inversion and buffer overrun

Viewed 43

I created a function to reverse a string.

I know the code for this function is already available on the web but I'm starting to develop in C and I want to do my functions to understand what I'm doing.

My Code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


char* reverseString(char* chaineFonc);
    
    char* reverseString(char* chaineFonc)
    {
        // Initialization
        int stringLength = strlen(chaineFonc);
        char* response = (char*)malloc((stringLength + 1) * sizeof(char));
        int numCarac = stringLength - 1;
    
        // For each Character in the String
        for (int i = 0; i < stringLength; i++)
        {
            // Memorization
            response[i] = chaineFonc[numCarac];
    
            // Decrement
            numCarac--;
        }
        // End - For each Character in the String
    
        // Finalization
        response[stringLength] = '\0';
    
        return response;
    }


    int main(int nbArg, char** listeArg)
    {
        printf("\n%s",reverseString("ABCDEFGHIJKLMN"));
    }

This code works but I have an alert under Visual Studio which indicates a buffer overflow when I have this code response[stringLength] = '\0';

And I don't understand why.

The Warnings :

Avertissement C6011 Déréférencement du pointeur NULL 'response'. (Dereferencing NULL pointer 'response')

Avertissement C6386 Dépassement de la mémoire tampon lors de l'écriture sur 'response'. (Buffer overflow while writing to 'response')

1 Answers

You should have told us you were running the static code analysis which probably gave you these warnings:

C:\Users\XXX\main.c(30): warning C6386: Buffer overrun while writing to 'response':  the writable size is '((stringLength+1))*sizeof(char)' bytes, but 'stringLength' bytes might be written.
C:\Users\XXX\main.c(30): warning C6011: Dereferencing NULL pointer 'response'. 

You get warning C6011 because response can potentially be NULL, because malloc may return a NULL pointer, although this is very unlikely to happen, especially as the allocaterd size is very small.

You can get rid of this warning by adding some code:

...
char* response = (char*)malloc((stringLength + 1) * sizeof(char));

if (response == NULL)  // <<< add this
  exit(1);             // <<< add this

int numCarac = stringLength - 1;
...

Warning C6386 is certainly a bug of the Microsoft static code analyzer, I don't see any problems in this code. Especially as the following error message is contradictory:

`the writable size is '((stringLength+1))*sizeof(char)' bytes,
 but 'stringLength' bytes might be written`
Related