Home > Blockchain >  Dynamic memory allocation using malloc() in C program
Dynamic memory allocation using malloc() in C program

Time:09-27

I have the following statement in a C program, for which *size is a number of bytes. The reason it is *size is because, size is an argument for the C function from a Fortran 77 code. Fortran sends the memory address of size to C program and *size is the value it holds which is the number of bytes (*size = 1138280).

ptr = malloc(*size)

printf("ptr= %ld,", ptr);

The printout gives a number for ptr

ptr = 46912496308240

What does this number represent?

CodePudding user response:

The printout is telling you the value of the variable ptr if you interpret it as an integer.

The %ld tells the printf() function to print the value as a 'long decimal'. The 'long' part is there because the value of ptr is 8 bytes (since it has type void *), and the normal %d decimal option is for 4 byte. The 'decimal' part means the output will be base 10 (the standard way of writing numbers).

The value that is printed out is the address in memory that ptr is pointing to. The malloc function is creating a bunch of space in memory that you can use, and ptr tells you where it is.

CodePudding user response:

The value of a pointer represents an address in memory. Each C implementation may decide for itself how the pointer represents an address, but it is common in modern C implementations that the bytes of the address space are effectively numbered with consecutive integers starting from zero, and the bits representing a pointer are that address in binary. In effect, a pointer “value” of 46,912,496,308,240 means the byte number 46,912,496,308,240 byte in the address space.

Note this does not mean your system has 46,912,496,308,241 bytes of memory; not all of the address space is used. Different parts of the memory of a process (such as initialized data, code, stack, and dynamically allocated memory) are started at different places so they have room to grow without bumping into each other. This leaves gaps where the address space is not mapped to usable memory.

You should not print a pointer by formatting it with %ld. Correct ways to print a pointer include converting it to void * and using %p:

printf("ptr = %p\n", (void *) ptr);

or converting it to uintptr_t and using "%" PRIxPTR, after including <inttypes.h> and <stdint.h>:

printf("ptr = %" PRIxPTR "\n", (uintptr_t) ptr);
  • Related