I have noted that, when writing a string in an array allocated with malloc()
, its value changes. To be clear, here is the code that replicates this \"error\":
The string literal "something"
represents a null-terminated series of characters that live in some read-only region (most likely .text
if you build/link/run on a GNU/Linux system).
Initially, a_p
points to somewhere in the memory region within which malloc
is allocating buffers. You can freely write to the location to which a_p
points, free()
it, etc. When you perform the assignment a_p = "something";
, you are not writing characters to the location to which a_p
points, but rather changing that pointer to point to the beginning of that string. Now, you're pointing into (read-only) memory that wasn't allocated by malloc
so its corresponding free
function isn't able to do anything meaningful.
Use strcpy
(or better yet for safety, strncpy
) instead to copy characters to the destination, a_p
.