I try to implement a simple program that returns a reversed copy of string. Everything went well except a Segmentation fault at the end!! It I comment the last free(), nothing looks wrong but I know it is not right.
#include <stdio.h>
#include <stdlib.h>
void revStr(char *str, char *newStr, int *idx)
{
if( *str != '\0')
{
*idx = *idx+1;
revStr(str+1, newStr, idx);
printf("char=%c int=%d\n", *str,*idx);
newStr[*idx]=*str;
*idx = *idx+1;
}
else if (*idx !=0)
{
printf("End Size=%d\n",*idx);
newStr = (char*)malloc( sizeof(char) * (*idx) );
*idx=0;
}
}
int main(void) {
int idx =0;
char * in = "This is a test string.";
char * out;
revStr(in, out, &idx);
printf("Out:%s\n", out);
free(out);
return 0;
}
char=. int=0
char=g int=1
char=n int=2
char=i int=3
char=r int=4
char=t int=5
char=s int=6
char= int=7
char=t int=8
char=s int=9
char=e int=10
char=t int=11
char= int=12
char=a int=13
char= int=14
char=s int=15
char=i int=16
char= int=17
char=s int=18
char=i int=19
char=h int=20
char=T int=21
Out:.gnirts tset a si sihT
Segmentation fault (core dumped)
I tried to figure out from couple of question but in vain. Can someone help??