0

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 seems to me malloc in some cases allocates too much memory, but I don't quite grasp why.

Examples:

repeater("hi", 2) -> hihi

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

The code:

int length(char* str)
{
    int i;
    if(str == NULL)
        return 0;
    for(i = 0; *(str+i) != '\0'; ++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;
}
Aphex
  • 408
  • 1
  • 5
  • 17
  • 4
    You must null-terminate the result string. – 500 - Internal Server Error Jul 27 '18 at 08:06
  • 1
    Are you sure you are allocating sufficient space? What about the terminating character (i.e. `\0`) of the resulting string? – ilim Jul 27 '18 at 08:07
  • 4
    Why not use [`strlen`](https://en.cppreference.com/w/c/string/byte/strlen) ? Why not use the more readable `str[i]` instead of `*(str+i)` ? – Sander De Dycker Jul 27 '18 at 08:12
  • Appending the null character seems to terminate the resulting string correctly and therefore solves my issue. Thank you! @Sander: Purely to get acquainted with C and how it deals with pointers and whatnot :-) – Aphex Jul 27 '18 at 08:16

1 Answers1

-1

You don't need the length function, strlen already do that for you AND it dont include the terminating null character.

so len = length(str); become len = strlen(str);

You need the string.h lib to work with it.

Look at this online version to see the change : https://www.jdoodle.com/embed/v0/AiA

Maximilien Nowak
  • 113
  • 1
  • 1
  • 8
  • Thanks for your input, Maximilien. As stated above it was intended as an exercise to get acquainted with the C language. I'm aware that C has quite some libraries with similar functionalities, but that wasn't maybe too clear from the context. – Aphex Jul 27 '18 at 09:20