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')