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.
Im certain it has something to do with malloc but I am not sure.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); }
What can I do to fix this? Thanks!



LinkBack URL
About LinkBacks



