0

I have a short snippet where I am passing a char array into another function and changing the size in memory.

// in main
char *str = argv[1];
find(&str);

void func(char **str){
  // some code
  *str = realloc(*str, 10+1);
}

This gives the error

realloc(): invalid pointer
Aborted (core dumped)

What did I do wrong here? In order to change the value of str in another function, I am using a double pointer.

shurup
  • 751
  • 10
  • 33
  • 8
    You can only reallocate an array that was allocated with `malloc`. `argv[1]` is not dynamically allocated. – Barmar Feb 20 '20 at 03:06
  • @Barmar being pedantic, it might be dynamically allocated, but not in a way that it can be `realloc()`ed, or `argv[]` might be in read-only memory, etc, etc. – Ken Y-N Feb 20 '20 at 03:07
  • 2
    @KenY-N It's not specified to be dynamically allocated, so you can't assume it is. So as far as being able to call realloc, it should be considered not dynamically allocated. – Barmar Feb 20 '20 at 03:20
  • 2
    Note on `realloc` (not your primary issue, but...). Do NOT `realloc` to the original pointer, e.g. don't do `*str = realloc(*str, 10+1);` instead, use a temporary pointer, e.g. `void *tmp = realloc(*str, 10+1);`, then validate the reallocation `if (tmp == NULL) { /* handle error - return or exit */ }; *str = tmp;` That way when `realloc` fails, you don't overwrite your original pointer with `NULL` losing the address to the prior allocated block creating a memory leak. – David C. Rankin Feb 20 '20 at 03:30
  • 2
    @KenY-N: it can't be in read-only memory. Sect 5.1.2.2.1; "The parameters **argc** and **argv** and the strings pointed to by the **argv** array shall be modifiable by the program, and retain their last-stored values between program startup and program termination." – rici Feb 20 '20 at 05:38

1 Answers1

3

What did I do wrong here?

*str in realloc(*str, 10+1) was not allocated by this process. @Barmar

Your code could have used the below or equivalent to allocate its own copy to later reallocate it. As strdup() is not in C STL as of C17, a sample implementation.

char *str = strdup(argv[1]);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256