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\":
You are changing the pointer directly. This statement
a_p = "something";
is equivalent to
a_p = &"something"[0];
String literals have types of character arrays. For example the string literal "something"
has type char[10]
.
From the C Standard (6.4.5 String literals)
6 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals.78) The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence...
Used in expressions arrays with rare exceptions are converted to pointers to their first elements.
From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
So after this statement
a_p = "something";
the pointer points to the first character of the string literal with the static storage duration.
I think you mean
strcpy( a_p, "something" );
That is you wanted to copy the string literal in the dynamically allocated memory.
Take into account that if even you'll write the following code
char *p1 = "string";
char *p2 = "string";
then it is not necessary that p1
is equal to p2
because depending on compiler options the compiler can place these two identical string literals in different memory extents.
So the if statement
if ( p1 == p2 )
can yield either true
or false
.