Home > Net >  Can't assign character while iterating through char pointer
Can't assign character while iterating through char pointer

Time:07-25

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;
}

CodePudding user response:

The line

char *str = "my_program -f 1 -o out.txt";

will create a string literal and make str point to that string literal.

Your program is not allowed to modify a string literal. Any attempt to do so will invoke undefined behavior.

You are passing a pointer to the string literal to the function split, which then attempts to modify the string literal. Therefore, your program is invoking undefined behavior. This is probably the reason why you are getting a segmentation fault.

In order to fix this, you should not create a string literal. Instead, you should create a normal array which can be modified, for example like this:

char str[] = "my_program -f 1 -o out.txt";
  • Related