Memory Functions - Still Learning

This is a discussion on Memory Functions - Still Learning within the C Programming forums, part of the General Programming Boards category; This won't work because you asked memory for 1 int, not 3. As I like to see pointers... Imagine a ...

  1. #31
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,184
    This won't work because you asked memory for 1 int, not 3.

    As I like to see pointers...
    Imagine a big city. The city must be addressable (ie, each part of it must have an address). This is so someone knows where to go if you describe it (memory address).
    Then let's imagine they need to build stuff. Houses, offices, factories, stores, etc (variables).

    So let's say then that you are the head of a building company. You want to build something. But you simply do not have permission to just go and build somewhere somewhere. No sir. If you do, the police will arrest you (the OS will shut down your program).
    Instead, you ask permission to build a number of buildings (next to each other). Say, 3 houses. The state then gives you clearance to build, and later, destroy what you build, and an address where these houses may be built (you call malloc/calloc).
    So, you send your working team there and they build the houses (you assign values in the requested memory). But since you ask to build 3, you only have permission to build 3 and no more. If you try to build more, the police will arrest you.
    Now, these houses will remain there, forever (let's forget the fact that they need maintenance). And they hog valuable space in the city. Eventually, if you keep building, there's not going to be any space left (you run out of memory).
    So you then need to destroy those houses to eventually build other things there. And having destroyed them, you no longer have permission to build there. If you do, the police will arrest you.

    This theory can be applied to dynamic memory.
    The big city is the computer memory.
    The police is the operating system.
    Addresses are pointers.
    Houses are variables such as int, float, char.
    Permission is given by malloc/calloc.
    You send your team to build the house by storing data using the dereference operator (*).
    You destroy what you built with free.

    So you request space in memory with malloc.
    You store the address in a pointer.
    You dereference the pointer to store a value.
    You call free to get rid of the memory you no longer need.

    Also, as you know, it is possible to get away with doing something illegal without the police catching you (your program may crash, and it might not). You might get away with it, and you might not. But you should keep yourself to within the walls of the law (then there will be 0% chance of your app crashing).
    Doing something illegal is often caused undefined behavior in the programming world (because it might lead to undesired results, and it might not).
    Last edited by Elysia; 08-29-2008 at 04:17 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  2. #32
    Odd Mental Process Alexander's Avatar
    Join Date
    Aug 2008
    Posts
    22
    Huh.. Weird.. I think I get it now.. ^^;
    Was this pre-written somewhere? Because this odd explanation actually helped a lot for some reason if this is all true. xD

    *bookmarks*

  3. #33
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,184
    It is true. It's how it's done.
    And it's actually an analogy I've thought up myself.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  4. #34
    Odd Mental Process Alexander's Avatar
    Join Date
    Aug 2008
    Posts
    22
    Lol well it helped a bunch. It was a great analogy. Thanks.

  5. #35
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    And in this analogy, the Heap is "free land that doesn't have any building on it".

    In a modern OS, it's probably a bit wrong to say "the heap", because there is no such thing. In old systems, there would literally be a chunk of memory called the heap (and when that was used up, then that was it). In a modern system, "the heap" isn't a pre-assigned piece of memory, instead the OS will dole out new pieces of memory as and when the application asks (subject to availability of course). Of course, there is a limit to how much memory you can use even in a modern OS, but it's not a preset limit at the time of building the application.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #36
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,184
    Oh yes, and though mats says technically it has no space - in every city, there is space take for other things than your own.
    Some space in the city is reserved, and some space is used to store information needed by the application, OS or some other parts, yet which you did not request.
    So there's no infinite free space to build in the city, but there is a lot.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  7. #37
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,189
    Quote Originally Posted by matsp View Post
    And in this analogy, the Heap is "free land that doesn't have any building on it".

    In a modern OS, it's probably a bit wrong to say "the heap", because there is no such thing. In old systems, there would literally be a chunk of memory called the heap (and when that was used up, then that was it). In a modern system, "the heap" isn't a pre-assigned piece of memory, instead the OS will dole out new pieces of memory as and when the application asks (subject to availability of course). Of course, there is a limit to how much memory you can use even in a modern OS, but it's not a preset limit at the time of building the application.

    --
    Mats
    Wrong. There is a 2GB(3GB) per process limit in 32 bit windows. 32 bit linux has a similar per process limit, although im nto sure what it is. The Heap is a preassigned area of memory. So is the stack. The stack grows down, the heap grows up. At least on intel compatible machines. The heap isnt assigned to a specific physical address in hardware, but it is assigned to a fixed address for a particular process relative to the local process memory.
    Until you can build a working general purpose reprogrammable computer out of basic components from radio shack, you are not fit to call yourself a programmer in my presence. This is cwhizard, signing off.

  8. #38
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by abachler View Post
    Wrong. There is a 2GB(3GB) per process limit in 32 bit windows. 32 bit linux has a similar per process limit, although im nto sure what it is. The Heap is a preassigned area of memory. So is the stack. The stack grows down, the heap grows up. At least on intel compatible machines. The heap isnt assigned to a specific physical address in hardware, but it is assigned to a fixed address for a particular process relative to the local process memory.
    No, it's not assigned a particular address - in windows you do "HeapCreate" to allocate a heap, whilst there are some heuristics in that function that gives you the same address for the application every tie, you can't write your own malloc and just start using a chunk of memory that starts just after the code [or some other address] - that memory isn't usable until you nicely request the OS to make it available to you. HeapCreate, however, will assign/reserve a virtual address range to the heap memory that is created. And just like if you call rand() without calling srand(), it gives the same address each time.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #39
    Odd Mental Process Alexander's Avatar
    Join Date
    Aug 2008
    Posts
    22
    Code:
        char string[256];
        char string = malloc(sizeof(int) * 256);
    So, these are essentially the same thing right?
    "Some people just don't get my humor. I always think that I'm funny. I've decided that the main reason why I go on the internet and socialize, is to legitimately talk to myself."

  10. #40
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Not really.

    First of all, this
    Code:
    char string = malloc(sizeof(int) * 256);
    is allocating enough space for 256 ints, not 256 chars. ints take more space than chars.

    Secondly, it would really have to be
    Code:
    char *string = malloc(sizeof(int) * 256);
    because you need a pointer to chars, not just a single lonesome char.

    Now, malloc() always allocates memory from the "heap". Declaring an ordinary variable as you have done in your first example, however, might allocate memory from the stack (if it's an automatic variable, i.e. declared inside a function), or from the heap (if it's a global or static variable).

    [edit] Take this example:
    Code:
    #include <stdlib.h>
    
    char heap1[256];
    
    int main() {
        char stack[256];
        char *heap2 = malloc(256);
        free(string);
        return 0;
    }
    As you can guess from their names, stack is on the stack and heap1 and heap2 are on the heap. [/edit]
    Last edited by dwks; 08-31-2008 at 04:15 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #41
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by dwks View Post
    Now, malloc() always allocates memory from the "heap". Declaring an ordinary variable as you have done in your first example, however, might allocate memory from the stack (if it's an automatic variable, i.e. declared inside a function), or from the heap (if it's a global or static variable).

    [edit] Take this example:
    Code:
    #include <stdlib.h>
    
    char heap1[256];
    
    int main() {
        char stack[256];
        char *heap2 = malloc(256);
        free(string);
        return 0;
    }
    As you can guess from their names, stack is on the stack and heap1 and heap2 are on the heap. [/edit]
    I'd say that "heap1" is allocated in "data", which is neither heap nor stack. Ok, so if heap1 is large enough to matter, it would "eat up" heap-space, but it wouldn't be on the heap.

    Maybe I have a different view of what "heap" is, but to me there are [at least] four distinct bits of memory in any application when it's running:
    * Code
    The instructions that tell the computer what you want done - the functions you have written in the application, C-library functions etc.
    * Data
    Global data, static variables, string literals, etc.
    * Heap
    Free space. Not used for anything until the application specifically asks (through malloc etc).
    * Stack
    Local variables and call-stack (where to return to from each function).

    These doesn't have to have any particular order, but normally, the code is in the lowest address, then data, then heap and the stack is located at a high address. That is the convention, but it doesn't have t be that way for any technical reason (generally speaking).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #42
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    I guess you're probably right. Although I've seen quite a few sources that say global variables are on the heap, it's not really accurate.
    Therefore, global variables (storage class external), and static variables are allocated on the heap.
    http://www-ee.eng.hawaii.edu/Courses...on2.1.1.8.html
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  13. #43
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    It is not how I would describe it. There is certainly a DATA segment in all of Windows, DOS, and Linux executables (and several other Executable formats I've worked with). That segment, depending on the OS architecture, may or may not be adjacent to the Heap. There may also be a "BSS" section (which is sometimes called something different), which is the "zero initialized data" - typically uninitialized global data.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  14. #44
    Registered User
    Join Date
    Mar 2008
    Posts
    11
    this is excellent. I just set out to find the difference between malloc and declaring variables (and why you don't free variables), and here is it after a short search. I didn't realise the difference between heap and stack.

    One question. If I have allocated some memory with malloc, and I then interrupt the program (Ctrl-c), what happens to the memory I've grabbed? If I am testing some code, and regularly interrupting it before completion, do I risk losing/leaking memory?

    cheers,

  15. #45
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,184
    The OS will clean up, so you don't lose any memory.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

Page 3 of 4 FirstFirst 1234 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-06-2009, 11:27 AM
  2. Reallocating Memory
    By Booie2k1 in forum C Programming
    Replies: 3
    Last Post: 03-11-2008, 06:09 AM
  3. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 12:33 PM
  4. Accessing Video Memory Information...need help
    By KneeLess in forum C++ Programming
    Replies: 8
    Last Post: 08-24-2003, 03:53 PM
  5. Manipulating the Windows Clipboard
    By Johno in forum Windows Programming
    Replies: 2
    Last Post: 10-01-2002, 09:37 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21