Why should I use the Free Space (heap)

This is a discussion on Why should I use the Free Space (heap) within the C++ Programming forums, part of the General Programming Boards category; I am reading a book and there is a chapter about pointers. I have grasp the main idead of a ...

  1. #1
    Registered User
    Join Date
    Aug 2007
    Posts
    66

    Why should I use the Free Space (heap)

    I am reading a book and there is a chapter about pointers. I have grasp the main idead of a pointer which hold the memory address of another variable or object. But, later, in the book, is says that all these local variables are destroyed after the function call. Ok, I already knew that. Also it says that a way to fix that is using global variables stored in namespace or use pointers to store the data in heap section .

    Could you tell me why I should want to use heap section instead of stack section ?


    If the problem is the destroyed data after return, I think that I can bypass this problem using parameters instead of using pointers in order to store the data in heap section. The parameters are not destroyed, right ?

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    One reason you'd want to use static or global variables when the variable must retain its value between function calls or sections of code. For example, if you had a function which had special initialization code, you might use something like this:
    Code:
    void func() {
        static int init = 0;
    
        if(!init) {
            // init code
            init = 1;
        }
        else {
            // normal code
        }
    }
    Obviously if the variable init did not retain its value across function calls, the construct would be of little use because the function would either always or never use the initialization code.

    If the problem is the destroyed data after return, I think that I can bypass this problem using parameters instead of using pointers in order to store the data in heap section. The parameters are not destroyed, right ?
    Yes, but then the calling function has to store the values. If the function is called from multiple places, or whatever, then this could be quite difficult.
    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.

  3. #3
    Registered User
    Join Date
    Aug 2007
    Posts
    66
    [QUOTE=dwks;669880]One reason you'd want to use static or global variables when the variable must retain its value between function calls or sections of code. For example, if you had a function which had special initialization code, you might use something like this:
    Code:
    void func() {
        static int init = 0;
    
        if(!init) {
            // init code
            init = 1;
        }
        else {
            // normal code
        }
    }
    Obviously if the variable init did not retain its value across function calls, the construct would be of little use because the function would either always or never use the initialization code.[quote]

    In this example you gave me, the init code is executed. So what's the point ? Do you mean using the int init variable later, in some other function without have to redeclare and initialize her - just retain the same value ( init = 1; ) ?

    You can do this by a global variable. Don't you ?

    Yes, but then the calling function has to store the values. If the function is called from multiple places, or whatever, then this could be quite difficult.
    So, if I want to built a simple programm about 200 lines of code, should I use stack or heap ? I mean, when should I understand that : "Hey, a pointer to this Class should be better here " ?

  4. #4
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,270
    Quote Originally Posted by BlackSlash12 View Post
    Could you tell me why I should want to use heap section instead of stack section ?
    Dynamic memory is useful when you are not certain ahead of time how many objects -- or what kind of objects -- your program is going to need.

    If the problem is the destroyed data after return, I think that I can bypass this problem using parameters instead of using pointers in order to store the data in heap section. The parameters are not destroyed, right ?
    You can do things that way. I tend to do things that way a lot in C. But your question isn't really clear enough to know for sure what you mean.

  5. #5
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,270
    Quote Originally Posted by BlackSlash12 View Post
    So, if I want to built a simple programm about 200 lines of code, should I use stack or heap ? I mean, when should I understand that : "Hey, a pointer to this Class should be better here " ?
    You should be able to write even fairly complex code without using pointers at all, if you take advantage of the STL containers. If you're not exactly sure why you need a pointer, you don't need a pointer.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,265
    So, if I want to built a simple programm about 200 lines of code, should I use stack or heap ? I mean, when should I understand that : "Hey, a pointer to this Class should be better here " ?
    I think we need some context to answer that. Take for example these two simple problems:
    A) Write a program that reads in 10 integers from a file and prints the median value of the integers. Assume that the file contains only and exactly 10 space separated integers.

    B) Write a program that reads n+1 integers from a file and prints the median value of the last n integers. n is the first integer read. Assume that the file contains only and exactly n+1 space separated integers, and that n > 0.

    Both A and B can be solved in much less than 200 lines of code. However, one would probably use a dynamic array (i.e., memory on the heap), or a container that is based on a dynamic array, to solve B, but could very easily get away with a statically allocated array for A (i.e., memory on the stack).
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Aug 2007
    Posts
    66
    Well I am just a novice in programming in C++ and in programming generally. I think that I should go with the example of my book until I finish it. I think that I am not able to choose between stack or heap because I have not face complex situations.

    Thank you all.

  8. #8
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    With very simple programs you are unlikely to use the heap, but when, as you say, programs become more complex it is invaluable.
    Imagine you have a function that given a filename will create an object for you that contains that files data. Rather than creating the object yourself and then passing it into the function, you could have the function allocate the object on the heap and then return a pointer to it. Passing a pointer is *much* more efficient than copying an entire object.
    That's just an example. I'm sure later on in your book you'll find out clearer scenarios where heap memory is useful.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Allocating large amounts of memory, or making an object's lifetime longer than the scope in which it was created are two reasons for heap-based memory. However, in many situations you are better off creating a smart class on the stack that handles the heap memory for you. Smart pointers and STL containers are examples of such classes that you would use. The memory they hold will be on the heap, but those objects themselves would be stack based.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. free() doesn't seem to work...
    By AlienJedi in forum C Programming
    Replies: 10
    Last Post: 01-29-2008, 05:27 PM
  2. Program that displays amount of free memory
    By trancedeejay in forum Linux Programming
    Replies: 3
    Last Post: 01-13-2006, 01:27 PM
  3. disk space mysteriously gone
    By evader in forum C++ Programming
    Replies: 4
    Last Post: 01-21-2004, 01:30 PM
  4. Help needed with backtracking
    By sjalesho in forum C Programming
    Replies: 1
    Last Post: 11-09-2003, 06:28 PM

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