0

I write a code to split string by delimiter. I want the function get a string and return its strings divided.

It actually works except for one thing. when I give string "test", it works. but when I give string "1234 4567", I can access the value '4567', but not '1234'. (garbage value.) also "1234 2345 3456 ..." results garbage value in only first argument '1234'.

I thought that using malloc() twice causes problem in the same pointer, but it doesn't. What is the problem for my codes?

char    **ft_set_char(char *str)
{    
    int     i;
    int     j;
    int     k;
    char    *str_c;
    char    **ret;

    k = 0;
    j = 0;
    ret = (char **)malloc(10);
    str_c = (char *)malloc(5);
    i = 0;
    while (*(str + i) != '\0')
    {    
        if (*(str + i) == ' ')
        {
            *(str_c + k) = '\0';
            k = 0;
            *(ret + j) = str_c;
            j++;
            i++;
            str_c = (char *)malloc(5);
        }
        *(str_c + k) = *(str + i);
        i++;
        k++;
    }
    *(str_c + k) = '\0';
    *(ret + j) = str_c;
    *(ret + j + 1) = NULL;
    return (ret);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Causing malloc twice shouldn't cause any problems. It just means that str_c now points to the newly allicated memory space. Although I can't test your code right now and it looks like there could occur quite a few problems it might actually work in your supplied example.. You definitely have to replace the size in the mallocs though by stating the correct size, that is: 10 * sizeof(char*) and 5 * sizeof(char). can you give the full code including the function declaration and how you access the values? – wschopohl Feb 01 '20 at 09:12
  • Your first `malloc` call is wrong. Should be `malloc(10*sizeof *ret)`. – kaylum Feb 01 '20 at 09:12
  • You example is incomplete without the calling code. I guess one of the core mistakes is to be found there. – cmaster - reinstate monica Feb 01 '20 at 09:21
  • Thanks all for comments. I was confused how to use malloc. and I solved problem for you. – Kyung Kyu Lee Feb 01 '20 at 10:09

1 Answers1

0
ret = (char **)malloc(10);

That is not correct because it allocates 10 bytes and not 10 char * elements. It should be:

ret = malloc(10 * sizeof *ret);

Other unrelated issues but should be noted for best practice:

  • Don't cast the result of malloc
  • Don't use magic numbers like 10 and 5. For the former at least use a #define MAX_ARRAY_SIZE 10. For the latter, you can keep work out the exact size of the string to be copied from the original str - that will make your code more robust in case it is ever used with longer sub-strings.
kaylum
  • 13,833
  • 2
  • 22
  • 31