Writing a string repeater in C produces unwanted chars

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Writing a string repeater in C produces unwanted chars



I'm trying to get a custom string repeater to work in C. It works for some input, and in other cases it appends unwanted characters. It seem to me malloc in some cases allocates too much memory, but I don't quite grasp why.


malloc



Examples:



repeater("hi", 2) -> hihi


repeater("hi", 2) -> hihi



repeater("yeah", 4) -> yeahyeahyeahyeah?f{??


repeater("yeah", 4) -> yeahyeahyeahyeah?f{??



The code:


int length(char* str)
{
int i;
if(str == NULL)
return 0;
for(i = 0; *(str+i) != ''; ++i);
return i;
}

char* repeater(char* str, int times)
{
char* out;
int i,len,sz;
len = length(str);
sz = len * times;
out = (char*)malloc(sz * sizeof(char));
for(i = 0; i < sz; i++)
*(out+i) = *(str + (i % len));
return out;
}









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

Future solutions