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.
malloc.argv[1]is not dynamically allocated.realloc()ed, orargv[]might be in read-only memory, etc, etc.realloc(not your primary issue, but...). Do NOTreallocto 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 reallocationif (tmp == NULL) { /* handle error - return or exit */ }; *str = tmp;That way whenreallocfails, you don't overwrite your original pointer withNULLlosing the address to the prior allocated block creating a memory leak.