//////
char* duplicate(char* string, int count)
{
char* duped = (char*) malloc( sizeof(char)*(count*strlength(string)+1) );
int i=0,j=0,t=0;
for( i=0; i<count*strlength(string); i++,j++ )
{
if (j==(strlength(string)))
{
j=0;
t++;
}
if (t==count)
{
duped[i] = '\0';
break;
}
duped[i] = string[j];
}
return duped;
}
The above code works perfectly, but the one below gives a segmentation fault. What is the difference between them? Shouldn't a function stop when it see return?
char* duplicate(char* string, int count)
{
char* duped = (char*) malloc( sizeof(char)*(count*strlength(string)+1) );
int i=0,j=0,t=0;
for( i=0; i<count*strlength(string); i++,j++ )
{
if (j==(strlength(string)))
{
j=0;
t++;
}
if (t==count)
{
duped[i] = '\0';
return duped;
}
duped[i] = string[j];
}
}