While compiling and executing the below program i am getting a warning during compilation and seg fault during execution.
Warning
program.c: In function main:
program.c:17: warning: passing argument 2 of convertString from incompatible pointer type
line 17 is the call to convertString(input, &output);
attaching the debugger is can see the segfault is occuring at the below line
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400521 in convertString (input=0x7fffffffd100 "abcdefg", output=0x7fffffffd0f0) at program.c:9
9 **output = *input;
(gdb) s
#include<stdio.h>
#include<string.h>
void convertString(char *input, char **output)
{
if(strlen(input)== 0)
{
return;
}
**output = *input;
(*output)++;
convertString(input+1,output);
}
int main()
{
char input[] = "abcdefg";
char output[sizeof(input)];
convertString(input, &output);
printf("%s", output);
return 0;
}
Please help me where i am doing wrong.
strcpy, usestrlenis not a good idea. To prevent an undefined behaviour check the lenght with a max threshold or until you find a'\0'. Also beacuse each recursion re-callstrlen...double *; you are using pointer to char pointer