- #1
James889
- 192
- 1
Hi,
I'm trying to write a simple program for reversing a string stored in memory.
This is what I've come up with. For some reason this code coredumps, so something is wrong.
any ideas ?
I'm trying to write a simple program for reversing a string stored in memory.
This is what I've come up with. For some reason this code coredumps, so something is wrong.
any ideas ?
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *reverse(char *buf,unsigned int bufsize ){
/* Allocate memory for the reversed string */
char *ptr = (char *)malloc(bufsize);
/* Get the address of the last character in the buffer. */
int buffaddr = &buf[bufsize];
char *buffptr = (char *)buffaddr;
*ptr++ = *buffptr--;
return ptr;
}
int main(void){
char Buffer[100];
strcpy(Buffer,"a cup of coffee");
char *reversed = reverse(Buffer,sizeof(Buffer));
free(*reversed);
return 0;
}