Home > front end >  Is the pointer returned by Malloc() a constant pointer in C?
Is the pointer returned by Malloc() a constant pointer in C?

Time:10-28

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?

Nothing Nothing Nothing

CodePudding user response:

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.

CodePudding user response:

What malloc(MEM_SIZE) returns is not a constant, usually a "readable and writable" memory space address.

The size of the readable and writable space is MEM_SIZE. If the MEM_SIZE is exceeded, the program will throw a memory out-of-bounds error. With luck the program will crash, with bad luck you will feel fine.

  • Related