Memory Allocation: Understanding int*p and int x

  • Thread starter Thread starter camel-man
  • Start date Start date
  • Tags Tags
    Memory
AI Thread Summary
The discussion centers on memory allocation in C, specifically the use of pointers with `malloc` and variable references. When `malloc` is called, it allocates memory on the heap and assigns the address of this memory to the pointer, which initially contains garbage data until it is assigned a value. The conversation highlights the importance of pointers for creating dynamic data structures like linked lists and for efficient object referencing in C++. It also emphasizes that while global variables may seem convenient, they can lead to code that is difficult to manage and maintain. Overall, pointers are essential for effective memory management and data structure manipulation in programming.
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?
 
Technology news 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.
 
A major use of pointers is for building dynamic data structures such as linked lists.
 
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.
 
Back
Top