I need to convert a char* into char* [] in order to pass it as a function argument.
The following dummy code gives a segmentation fault in the marked line, I can not figure out why.
#include <malloc.h>
#include <stdio.h>
#include <string.h>
void f(char* const args[]){
for( int i = 0; args[i] != (char*)NULL; ++i ){
puts("x");
printf("%s\n", args[i]);
}
}
char** split(char* str, char tok){
int len = strlen(str);
printf("str: %s\n", str);
printf("len: %d\n", len);
int num = 2;
char* it = str;
for( int i = 0; i < len; ++i ){
printf("it: %s\n", it);
if( *it == tok ){
*it = '\0'; // SEGFAULT
num++;
}
it++;
}
printf("test\n");
char** result = malloc(num * sizeof(char*));
int j = 0;
int save = 1;
it = str;
printf("it: %s\n", it);
for( int i = 0; i < len; ++i ){
if( *it == tok ){
save = 1;
}
else if( save == 1 ){
result[j++] = it;
save = 0;
printf("save: %d %p %s\n", j, it, it);
}
}
result[j] = (char*)NULL;
return result;
}
int main (){
char *str = "my_program -f 1 -o out.txt";
char** split_str = split(str, ' ');
f(split_str);
return 0;
}