Re: C style , one argument, recursive, string reverse
zahy[dot]bnaya[At]gmail[dot]com schrieb:
All previous advices were good and appreciated..
Sorry about my stubborness I am really intrested to know why my code
does not work
I remarked it better.
I know it is probably not the best way to do it but can you see a
problem in there?
not for the sake of solving the problem , just for education...
Thanks.
Yes. You forget, that
a) you can't free() space you did't malloc().
b) strings are zero-terminated.
/*
Algorithm pseudo:
reverse(str)
if(str="")
// return ""
else
return append(last_char(str),
reverse(all_but_last_char(str))
*/
char * C_recReverse(char * str)
{
// Sub is storing the substring
// res is the returned string
// tmp is for storing the previos result so it can be deleted
char* sub, *res, *tmp;
if (strlen(str) == 0)
{
// return "";
res= (char*)malloc(1);
res[0] = '\0';
return res;
}
else
{
/* the sub and res are allocated per recursion stack*/
sub = (char*)malloc(sizeof(char)*strlen(str)-1);
res = (char*)malloc(sizeof(char)*strlen(str));
You will copy the entire string "str" into "sub", so "sub" has to hold
enough space for strlen(str)+1.
"res" has to hold "str" reverse, so dito.
sizeof(char) is defined to be 1.
/* prepering the substring, stored on the heap*/
strcpy(sub,str);
sub[strlen(str)-1] = '\0';
/* the return value is preperaed , filled with last char*/
strcpy(res,"");
strncpy(res,&str[strlen(str)-1],1);
Bad.
res is not null-terminated after this.
/* calling the reverse function of the "sub" stored
on local variable tmp*/
tmp = C_recReverse(sub);
/* adding the result of substring reverse to the result string (res)
*/
strcat(res,tmp);
/*"closing" the string (???) */
res[strlen(str)] = '\0';
/* Freeing the substring, I dont really need it anymore*/
free(sub);
/* Freeing the "previous" recursion closure,
Can I do it? I think this is the
problem */
free(tmp);
return res;
}
}
This is evil C++ code, and I think its evil C, too.
Thomas