Problem with split function in C

1

Hi, I'm studying C language and I came across a pointer problem in a string breaking function. I use the 4.8.4 GCC version. The input value that results in an error is "1234 | 123 | 123 | 123" 4/3/3/3, other values such as "1234 | 123 | 123 | 1234" 4/3/3/4 pass without error .

The code attachment follows.

#include <string.h>
#include <malloc.h>
#include <stdio.h>

char **split(const char *str, const char *chrs){
    char to_list[strlen(str)];
    char *ssplit;
    int x=0,y=0;
    char **res = 0;

    for(y=0;y<strlen(str);y++){
        if(str[y] == chrs[0])
            x++;
    }

    strcpy(to_list, str);
    ssplit = strtok(to_list, chrs);
    res = (char **) malloc(sizeof(char*)*(x+1));
    y=0;

    while(ssplit){
        res[y] = (char*) malloc(sizeof(char)*strlen(ssplit));
        strcpy(res[y],ssplit);
        y++;
        ssplit= strtok(NULL, chrs);
    }

    return res;
}
    
asked by anonymous 04.02.2016 / 16:07

1 answer

1
char to_list[strlen(str)];

The array to_list has space for strings up to strlen(str) - 1 length. If you put more characters there (including '%code%' ), you invoke Undefined Behavior.

strcpy(to_list, str); // BANG!, tentativa de colocar um caracter a mais em to_list
    
04.02.2016 / 17:21