Search code examples
cmallocrealloc

Realloc trouble


I have problem. I have stroke: "/hello/world" I need to copy word 'hello' to another string;

I have this code:

void copy(char *command) {// copy 
 char *word = NULL;
 int size = 1;
 if (*command == '/') {
    command++;
    while (*command != '/') {
         word = (char*)realloc(word, size * sizeof(char));
         *word = *command;
         size++;
         word++;
         command++;
     }
     printf("%s", word);
     free(word);
}

but I get this error: Segmentation fault (core dumped)

What I do wrong?


Solution

  • As @kaylum says the reason that you get the error is that you change the word pointer's value. When you reallocate memory for a allocated array of memory block and change the size of that memory block's size, realloc() changes the size and returns the pointer which points to first memory block of that allocated array. In this case if you want to change size of word's memory try using an index to access the newly added memory block.

        void copy(char *command) {// copy
          char *word = NULL;
          printf("%s\n",command);
          int size = 1,index=0;``
          if (*command == '/') {
            command++;
            while (*command != '/') {
              word = (char*)realloc(word, size * sizeof(char));
              word[index] = *command;
              size++;
              command++;
              index++;
            }
            printf("%s\n", word);
            free(word);
          }
        }