1
Hi, I’m studying the C language and came across a pointer problem in a string breaking function. I use the version GCC 4.8.4. The error value is "1234|123|123|123|123" 4/3/3/3, while other values like "1234|123|123|1234" 4/3/3/4, pass without error.
Follows the Annex to the Code.
#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;
}
It is important to code correctly. The above code can be syntactically valid, but it is difficult for people to read.
– jsbueno
Regardless of whether this function works - how will the functions you call it know the size of the returned res vector? Anyone consuming the result of this function would not know where to stop. Do you have how to put a minimally complete program that uses this function? (solvable making the size of res be
((sizeof(char*)*(x+2))
instead of(x + 1)
- and placing a NULL in last position)– jsbueno
this would really help identify the final position, but it was working with fixed values, and the error originated because of the type of input
– Brumazzi DB