Memory Allocation: Understanding int*p and int x

  • Thread starter Thread starter camel-man
  • Start date Start date
  • Tags Tags
    Memory
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 3K views
camel-man
Messages
76
Reaction score
0
int *p=malloc(sizeof(int));

and

int x;
int*p=&x;



I know that if you take the second one and print p it gives the address of x correct?
now what I want to know is when I malloc a pointer what address does it hold?? does it still hold the local address of p? Since I am not pointing it to a variable does malloc create memory that has an address and point it to that address on the heap?
 
on Phys.org
camel-man said:
int *p=malloc(sizeof(int));

does malloc create memory that has an address and point it to that address on the heap?

Yes, using the word "create" loosely. The memory is always there, of course; malloc() simply designates some unallocated ("unused") memory as now being allocated ("in use"). p now contains the address of the memory that was allocated.

The allocated memory contains random garbage (whatever bits happened to be at that location when it was allocated) until you store store something in it, with e.g. *p = 42.
 
Ok thank you jtbell, also I just don't really quite understand why we use pointers as far as the hardware level is concerned. how come every variable isn't global wouldn't that make more sense, eliminating pointers all together, but I am sure there are restrictions to be taken into consideration that I don't understand.
 
Another example would be an array of pointers to strings (of characters). In the case of a sort program, you could sort the pointers instead of the strings.
 
Another would be classes in C++. The "this" pointer used to allow methods to work on all instances of a class. They're also used in vtables which are what allow polymorphism to work.
 
Last edited:
pointers are also used as efficient object references.
making variables global is not a good practice. there are certain cases that it is a must but in general, it creates hard to understand, modify, maintain, test code. It basically oppositive of divide and concur.