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.

5
  • 8
    You can only reallocate an array that was allocated with malloc. argv[1] is not dynamically allocated. Commented Feb 20, 2020 at 3: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. Commented Feb 20, 2020 at 3: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. Commented Feb 20, 2020 at 3: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. Commented Feb 20, 2020 at 3: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." Commented Feb 20, 2020 at 5:38

1 Answer 1

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]);
Sign up to request clarification or add additional context in comments.

3 Comments

strdup is not in ISO C
Apparently it will be in C20.
@M.M Post amended to include that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.