-2

I'm attempting to split the string in "tmp" and put it into the array of pointers "arr". I'm doing this because I intend to used "execv" on "arr" but I can't because "arr" does not have NULL at the end. Instead it has "(null)" and when I print it's contents I get a segmentation fault. How would I set "arr" correctly so that it can be used with execv? Thanks

#include<stdio.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<string.h>

int main(){

    char tmp[40] = "echo Hello World \n ";
    char *arr[40];

    char *token = strtok(tmp, " \n");
    int index = 0;

    while(token != NULL){
        arr[index] = malloc(strlen(token) + 1);
        arr[index] = token;

        index = index + 1;
        token = strtok(NULL, " \n");
    }


    for(int i = 0; i < 40; i++){
        printf("%s \n", arr[i], arr[i]);
    }


    return 0;

}

1 Answers1

2

Here is a big problem:

arr[index] = malloc(strlen(token) + 1);
arr[index] = token;

You don't copy the string, instead you overwrite the pointer. You should use strcpy to copy the string:

strcpy(arr[index], token);

In this case it might not be needed to copy the strings though, just the assignment will do. That also means no allocation are needed.


There's also another problem with your code: The loop where you print the strings in arr.

With the string you have you should only have three elements valid in arr, the rest will be uninitialized and indeterminate. Dereferencing them (like you do when you attempt to print the "strings" they point to) will lead to undefined behavior.

After the previous loop, where you initialize arr, then index will be the number of valid elements in arr. Use that as the end of the printing-loop:

for(int i = 0; i < index; i++){ ... }
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621