Pointer to string changes its value unexpectedly

后端 未结 4 1457
执念已碎
执念已碎 2021-01-26 18:32

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\":

4条回答
  •  广开言路
    2021-01-26 19:26

    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.

提交回复
热议问题