Question

I need to save the contents of tmp to tmp2. However tmp is always NULL outside of the while loop.

if(1){

        char* tmp;
        char* tmp2;

        // split the string on the space character
        tmp = strtok(actual_args[0], " ");

        while(tmp != NULL){
            strcpy(tmp2, tmp);
            tmp = strtok(NULL, " ");                
        }


        // always NULL
        printf("%s", tmp);

        // produces seg. fault
        printf("%s", tmp2);



}
Was it helpful?

Solution

The problem with your code is that it is not using strcpy correctly: the function copies the content of the string, it does not create a copy of the string's memory.

It is your task to allocate the memory for the destination string. You could do it in the automatic memory (i.e. on the stack), in the static memory, or in the dynamic memory (i.e. the heap).

If you want to allocate dynamic memory for your string, you can do it like this:

char tmp2 = NULL; // Don't forget to initialize tmp2
...
while(tmp != NULL){
    free(tmp2);                   // Free the old content of tmp2
    tmp2 = malloc(strlen(tmp)+1); // Add one byte for null terminator
    strcpy(tmp2, tmp);            // Now the copy has space to which the data is copied
    tmp = strtok(NULL, " ");                
}
... // Use tmp2 ...
free(tmp2); // You need to free dynamically allocated memory

You could use the non-standard strdup function for this as well, but that is not recommended.

OTHER TIPS

If your goal is finding the last token:

// assuming actual_args[0] is a char *
char *lastToken = actual_args[0];
for (int i = 0; 0 != actual_args[0][i]; i++) {
    if (' ' == actual_args[0][i]) lastToken = &actual_args[0][i+1];
}

printf("%s", actual_args[0]);
printf("%s", lastToken);

If you want an array of all the tokens, you could do something like this:

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

#define MAX_TOKS 10

int main() {
  char *p, *toks[MAX_TOKS];
  char str[] = "a string to tokenize";
  int i, n = 0;

  p = strtok(str, " ");
  while (p) {
    if (n >= MAX_TOKS) {
      fprintf(stderr, "MAX_TOKS overflow\n");
      exit(EXIT_FAILURE);
    }
    toks[n++] = p;
    p = strtok(NULL, " ");
  }

  for (i = 0; i < n; ++i)
    printf("[%s]\n", toks[i]);

  return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top