Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Malloc in C

  1. Jan 28, 2012 #1
    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?
     
  2. jcsd
  3. Jan 28, 2012 #2

    jtbell

    User Avatar

    Staff: Mentor

    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.
     
  4. Jan 29, 2012 #3
    Ok thank you jtbell, also I just dont really quite understand why we use pointers as far as the hardware level is concerned. how come every variable isnt global wouldnt that make more sense, eliminating pointers all together, but I am sure there are restrictions to be taken into consideration that I dont understand.
     
  5. Jan 29, 2012 #4

    jtbell

    User Avatar

    Staff: Mentor

    A major use of pointers is for building dynamic data structures such as linked lists.
     
  6. Jan 29, 2012 #5

    rcgldr

    User Avatar
    Homework Helper

    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.
     
  7. Jan 29, 2012 #6
    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: Jan 29, 2012
  8. Jan 29, 2012 #7
    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Malloc in C
Loading...