Search code examples
arrayscpointersmallocimplicit-conversion

Is the pointer returned by `malloc()` a constant pointer in C?


I know that the name of an array is a constant pointer. I am wondering what is the case for the pointer returned by malloc()? Is it a constant pointer?


Solution

  • I know that the name of an array is a constant pointer.

    You are mistaken. Arrays are not pointers. But used in expressions with rare exceptions they are implicitly converted to pointers to their first elements that a rvalues. Arrays themselves are non-modifiable lvalues.

    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.

    The function malloc returns a value of the address of the allocated memory. It is not a constant pointer. But as it is an rvalue you may not assign a new value to the returned pointer.

    And as @John Bollinger correctly mentioned in a comment the return type of the function malloc is void * not void * const.