Heap Corruption Detected -- Malloc issues
Hi I wrote a program that takes a string of words and reverses the order of the words: String : two words ----> words two
The program seems to do what I intended but crashes right after with a HEAP CORRUPTION DETECTED error.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverseWord(char *string, int size);
int main(void){
int size;
char *string = "Two words";
size = (int)strlen(string);
reverseWord(string, size);
return 0;
}
void reverseWord(char *string, int size){
char *buffer;
int currentPos, endWord, startWord, bufferWrite = 0;
buffer = (char *) malloc(size);
currentPos = size - 1;
while(currentPos >= 0){
if(string[currentPos] == ' '){
buffer[bufferWrite++] = string[currentPos];
currentPos--;
}
else if(string[currentPos] != ' '){
endWord = currentPos;
while(currentPos >= 0 && string[currentPos] != ' '){
currentPos--;
}
startWord = currentPos + 1;
while( startWord <= endWord ){
buffer[bufferWrite++] = string[startWord++];
}
}
}
buffer[bufferWrite] = '\0';
printf("%s\n", buffer);
free(buffer);
}
Im certain it has something to do with malloc but I am not sure.
What can I do to fix this? Thanks!