Obviously my C skills have been on the shelf too long because i have been seriously looking at this code for about a week now (when I have the time) and STILL cannot find what the heck the problem is.
Can anyone see what I am doing wrong?
Hoping another set of eyes will see some simple mistake I've made.
The output is this:
If I remove the "free(str);" line in main it gets rid of the segfault but still only displays:
Why isn't it returning the proper string of length 4?
Thanks to anyone taking the time to read this.
.....It seems my account name is segfault for good reason
Can anyone see what I am doing wrong?
Hoping another set of eyes will see some simple mistake I've made.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int recursion(char *str, int ntoadd, int nreadsofar);
int main()
{
char *str;
int ret=0;
ret = recursion(str, 2, 0);
printf("final answer is (%d):%s\n", ret, str);
free(str);
}
int recursion(char *str, int ntoadd, int nreadsofar)
{
if(nreadsofar ==0)
{
str = (char *)malloc(ntoadd);
memset(str, 'a', ntoadd);
}
else
{
char *tmp = (char *)malloc(ntoadd + nreadsofar);
memset(tmp, 'b', ntoadd + nreadsofar);
strncpy(tmp,str,ntoadd + nreadsofar);
free(str);
str=tmp;
}
int x;
for(x=0; x<ntoadd; x++)
str[nreadsofar +x] = 'c';
if(nreadsofar +x < 4)
x = recursion(str, 2,nreadsofar + x);
printf("returning (%d):%s\n", x+nreadsofar, str);
return x;
}
The output is this:
Code:
returning (4):cccc
returning (2):cc
zsh: segmentation fault ./a.out
If I remove the "free(str);" line in main it gets rid of the segfault but still only displays:
Code:
returning (4):cccc
returning (2):cc
final answer is (2):%
Why isn't it returning the proper string of length 4?
Thanks to anyone taking the time to read this.
.....It seems my account name is segfault for good reason
