i've a char **array like this one :
{"first", "and", "second", "and", "third"}
and i'd like to free(array[3]) and put the pointer to array[1] inside. (because it's the same string).
i tried but the pointer wasn't modified. Can you help me pls, thanks.
Asked
Active
Viewed 27 times
-2

antocad
- 3
- 1
-
1You must not use `free()` on a pointer that wasn't returned by `malloc()`. It causes undefined behavior. – Barmar Oct 03 '17 at 19:26
-
Welcome to Stack Overflow. Please click [edit] and copy-paste the code that you tried unsuccessfully. Then select the code, click curly braces above the text editor, and click [Save]. – Sergey Kalinichenko Oct 03 '17 at 19:27
-
it's an example here, obviously my array was returned by malloc() . – antocad Oct 03 '17 at 19:28
-
Not the array, the string literals that the elements point to. – Barmar Oct 03 '17 at 19:31
-
just recreate the array minus the literal u do not need, new size would be array[4] instead of array[5] – Aaron. S Oct 03 '17 at 19:34
1 Answers
0
You can't free a pointer that wasn't allocated dynamically with malloc()
. Just reassign the pointer without using free
:
array[3] = array[1];
This won't likely save any memory, because string literals are allocated statically. And some implementations will merge equal string literals, see Addresses of two pointers are same, so it's effectively done the assignment that you want.

Barmar
- 741,623
- 53
- 500
- 612
-
ok thanks, finally my code was correct, just i was doing printf("%p",&array[i]) instead of printf("%p",array[i]) – antocad Oct 03 '17 at 19:39