Thread: Memory Allocation?

  1. #1
    Registered User
    Join Date
    Aug 2014
    Posts
    5

    Memory Allocation?

    So, coming from C# I'm trying to learn C++. I've been reading 'Jumping Into C++' and have gone through the three chapters covering Pointers, References, Arrays, and memory allocation. I am now hopelessly confused (I think), even after reading them three times.

    I get the basic idea that a pointer is a memory address to another variable.

    I also get the idea that a reference is a way to provide a variable with an 'alias' name, though I don't see at the moment what that's supposed to get me.

    Arrays? No problem, they're a sequential block of memory addresses.

    However, when it comes to memory allocation (Ch. 14 in the book), I'm not following. The book says that to allocate a block of memory for a pointer one needs to use the NEW keyword (e.g. int *ptr = new int). Ok, but doesn't declaring the pointer (e.g. int *ptr) do the same thing by default? It seems to me that unless one sets a pointer to NULL, it has something in it when it is declared, which means it has to have allocated memory.

    If that is true, then what is the reason for explicitly allocating memory with the NEW keyword?

    Wouldn't that effectively double the memory being 'consumed' by the pointer?

    I'm also not following why arrays appear to be treated differently with respect to pointers and memory allocation than any other variable type. It seems to me it's just a variable with a larger block of assigned memory. Why treat it differently?

    Clearly, I'm missing something...

  2. #2
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by A36 View Post
    I also get the idea that a reference is a way to provide a variable with an 'alias' name, though I don't see at the moment what that's supposed to get me.
    It's useful for passing as a parameter to a function that needs to update the object you already have. This functionality can be achieved with a pointer or a reference.

    Quote Originally Posted by A36 View Post
    Arrays? No problem, they're a sequential block of memory addresses.
    Wrong. An array is a block of objects. When referencing the block, you can either treat the name of the array as a pointer to the first element, or you can use the array as a first-class object.

    Quote Originally Posted by A36 View Post
    However, when it comes to memory allocation (Ch. 14 in the book), I'm not following. The book says that to allocate a block of memory for a pointer one needs to use the NEW keyword (e.g. int *ptr = new int). Ok, but doesn't declaring the pointer (e.g. int *ptr) do the same thing by default? It seems to me that unless one sets a pointer to NULL, it has something in it when it is declared, which means it has to have allocated memory.
    A pointer to int is not an int, in and of itself. The pointer is a distinct data type, that can be used to refer to an int anywhere in memory. In your case, using new creates a new int object on the heap, with your pointer referring to it.

    Quote Originally Posted by A36 View Post
    If that is true, then what is the reason for explicitly allocating memory with the NEW keyword?
    Because an int pointer does not contain an int value. It must point to a real int object somewhere. It's like the difference between my address and my house. My address points to my house, but it is not my house, in and of itself.

    Quote Originally Posted by A36 View Post
    Wouldn't that effectively double the memory being 'consumed' by the pointer?
    Maybe, depending on the size of a pointer and the size of an int.

    Quote Originally Posted by A36 View Post
    I'm also not following why arrays appear to be treated differently with respect to pointers and memory allocation than any other variable type. It seems to me it's just a variable with a larger block of assigned memory. Why treat it differently?
    Arrays and pointers to blocks of memory are different things. An array has a size that is known at compile time, while memory allocated by new, even if it is a block of memory containing multiple logical elements, is not an array.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by A36 View Post
    I get the basic idea that a pointer is a memory address to another variable.
    It's just a memory address and it has a type (integer, character, structure, ...) , except that a type of "void", is more like a non-type.

    I also get the idea that a reference is a way to provide a variable with an 'alias' name, though I don't see at the moment what that's supposed to get me.
    It's mostly an alternate syntax for a pointer, since most compilers will implement it as a pointer. However, unlike a pointer, a reference can only point to a specific object or variable, and it can't be changed to point to another object, variable, or allocated memory. One potential problem with this is that it's not possible to tell if a parameter is being passed by value or by reference in the calling function, you need to look at the called function or it's prototype.

    However, when it comes to memory allocation (Ch. 14 in the book), I'm not following. The book says that to allocate a block of memory for a pointer one needs to use the NEW keyword (e.g. int *ptr = new int). Ok, but doesn't declaring the pointer (e.g. int *ptr) do the same thing by default? It seems to me that unless one sets a pointer to NULL, it has something in it when it is declared, which means it has to have allocated memory.
    When a pointer is declared, it often will have some random uninitialized value, zero, or a debug value (like 0xcccccccc). Until you point it to an object or allocate memory for it via a new or a malloc(), it won't be useful.

    I'm also not following why arrays appear to be treated differently with respect to pointers and memory allocation than any other variable type. It seems to me it's just a variable with a larger block of assigned memory. Why treat it differently?
    Arrays are defined a compiler time either in the "data" section of a program if declared outside a function or as static, or on the stack if declared within a function (and not static). Memory is allocated from the "heap".
    Last edited by rcgldr; 08-28-2014 at 07:32 PM.

  4. #4
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    As another analogy -

    A pointer is like a street address. It can be anything, and there may or may not be anything at that address.

    "new" builds a house, and returns the street address of that house.

    When you only declare a pointer, it's just an address that doesn't point to anything (or points to some random place in memory that you have no access to).

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by A36 View Post
    I'm also not following why arrays appear to be treated differently with respect to pointers and memory allocation than any other variable type. It seems to me it's just a variable with a larger block of assigned memory. Why treat it differently?
    Because of carry over from C, which was made to deal with 80s performance considerations. When want array that act more like other objects, used std::array. I suggest using it whenever you can instead of raw arrays.

    There is another reason why pointers are special with arrays. A pointers is an iterator into an array. However, unlike other container types, you don't need a reference to the container object to get a pointer. Any block of continuous memory filled with the same type of object is logically an array that can be iterated through.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  6. #6
    Registered User
    Join Date
    Aug 2014
    Posts
    5
    Thanks to everyone for their responses. I'm trying to muddle through this, but still don't follow what the book is trying to prove or show. With respect to the pointer, from a memory standpoint there should be no difference between:

    int x = 5;
    int *y = &x;

    and:

    int *y = new int;

    In both cases the pointer is allocating memory at the time of declaration. In the first case it sets the address of 'x' to whatever memory location was assigned. In the latter case, the memory location is still assigned, there's just nothing useful stored in that location. Either way, the same amount of memory was allocated, and it was done so dynamically.

    Regarding the pointer/array relationship I'm still not following the point the book is trying to make. I can see what they're doing, and can follow it, but don't get why it's being given special emphasis. So the pointer points to the address of the first element in the array; ok, that's nice, but so what? The pointer points to the address of whatever variable its assigned.

    I shall continue to try to figure this out...

  7. #7
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by A36 View Post
    int x = 5;
    int *y = &x;

    and:

    int *y = new int;

    In both cases the pointer is allocating memory at the time of declaration.
    The pointer 'y' itself is allocated on the stack, as is 'x', so yes, memory is allocated in both cases, but in the second case, additional memory is allocated on the heap, and its address is now contained in the pointer 'y'.

    Quote Originally Posted by A36 View Post
    In the first case it sets the address of 'x' to whatever memory location was assigned.
    No. It doesn't "set the address" of anything. It stores the address of 'x' in the pointer 'y'. 'y' now points to 'x'.

    Quote Originally Posted by A36 View Post
    In the latter case, the memory location is still assigned, there's just nothing useful stored in that location.
    There's definitely something useful stored there, but it just doesn't have a defined value yet.

    Quote Originally Posted by A36 View Post
    Either way, the same amount of memory was allocated, and it was done so dynamically.
    In theory, yes, but only in the second example is it dynamic.

    Quote Originally Posted by A36 View Post
    So the pointer points to the address of the first element in the array; ok, that's nice, but so what?
    The pointer can be incremented to point at the subsequent elements, or you can use array notation to access individual elements.

    In your first example, try this:

    Code:
    int x = 5;
    int *y = &x;
    delete y;
    Then try this with your second example:

    Code:
    int *y = new int;
    delete y;
    What happens? Do you know why?
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  8. #8
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Assuming that all of these statements are within a function, then:

    Code:
    int x = 5;        // x resides on the stack, and contains the integer value 5
    int *y = &x;      // y resides on the stack, and contains a pointer to x
    
    // ...
    
    int *y = new int; // y resides on the stack, and contains a a pointer to an integer allocated from the heap
    About arrays and pointers. C treats the names of arrays as if they were pointers, with a known size of the array in many cases. If an array name is used as a parameter when calling a function, rather than passing the array by value, C passes the array by reference (by a pointer to the array). It's inconsistent with how C treats other variable types, such as a structure, which could include an array (in that case if the structure is passed as a parameter, the structure is passed by value (a copy of the structure is made)). For comparison, Fortran (at least the old versions) is consistent in that it passes all function parameters by reference. A interpretive language called APL passes all function parameters by value, and arrays of any number of dimensions can be assigned, used with the basic operators, or used as parameters in functions.
    Last edited by rcgldr; 08-29-2014 at 09:59 AM.

  9. #9
    Registered User
    Join Date
    Aug 2014
    Posts
    5
    So, I tried the two code examples you provided. The first example crashed with an error that appears to be 'corruption of the heap'. If I set pointer 'y' to NULL before deleting it, the code ran fine. In the second example, the code ran with no errors. I can only surmise the first code crashed because it was storing an actual address, while in the second example it was 'empty'. Why that should matter I don't know since 'x's address wasn't moved to pointer 'y', just copied; 'x' should still be intact.

    Ugh, pointers....

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by A36
    The first example crashed with an error that appears to be 'corruption of the heap'. If I set pointer 'y' to NULL before deleting it, the code ran fine. In the second example, the code ran with no errors. I can only surmise the first code crashed because it was storing an actual address, while in the second example it was 'empty'. Why that should matter I don't know since 'x's address wasn't moved to pointer 'y', just copied; 'x' should still be intact.
    The first example's problem is that the pointer points to an object whose storage was not allocated via new. Therefore, using delete on it results in undefined behaviour, one symptom of which is a crash. When you set y to be a null pointer, this problem disappears because using delete on a null pointer is safe and results in no net effect.

    The second example does not have the problem because the pointer points to an object whose storage was allocated via new, hence using delete is appropriate.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User
    Join Date
    Aug 2014
    Posts
    5
    Obviously (to me, anyway), there is some fundamental information I'm missing, or not able to discern from the book, as I am now even more confused than I was before starting this thread. I thought I understood pointers (finally), but clearly that is not the case. And this bit with memory allocation makes absolutely no sense. A program allocates memory when it starts, and allocates memory when it runs. It all ultimately comes from the 'heap'. I just don't get it.

    I'll just have to try to figure out what I'm missing and piece it all together from there.

    My thanks to everyone who replied for their help...

  12. #12
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    There are two places where memory can be allocated. The stack and the heap. Any non-static variable that you declare inside a function is allocated on the stack, even if it is a pointer. The pointer itself is on the stack, even though it may point to something on the heap.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You could read GotW #9: Memory Management - Part I for a brief overview.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by A36 View Post
    So the pointer points to the address of the first element in the array; ok, that's nice, but so what? The pointer points to the address of whatever variable its assigned.
    The pointer of type T * points to the address of a variable of type T in the general case. But an array of T is not the same thing. Yet a pointer of type T* can point to an array of T. That's different. It points to the first element of the array when an array is returned from new, and this provides a way to access all the elements in the array.

    It might also be confusing that we're talking about array as a logical type. There is no array object created with new, it's just a series of objects adjacent in memory that function like an array. As before, using std::array avoids this confusion.

    Quote Originally Posted by A36 View Post
    And this bit with memory allocation makes absolutely no sense. A program allocates memory when it starts, and allocates memory when it runs. It all ultimately comes from the 'heap'. I just don't get it.
    No, it doesn't all come from the heap. A program allocates some memory when it starts, which is used for static storage duration variable, such as global variables. It also reserves a stack, from which automatic storage duration variables are allocated; these are your run of the mill function variables. Lastly anything allocated with new is allocated on the heap. Each of these variables have a different lifetime which you have to be aware of.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory allocation
    By johnmerlino in forum C Programming
    Replies: 1
    Last Post: 04-05-2014, 02:45 PM
  2. memory allocation
    By mbooka in forum C Programming
    Replies: 3
    Last Post: 02-28-2006, 03:13 PM
  3. Memory allocation
    By swoopy in forum C++ Programming
    Replies: 9
    Last Post: 08-08-2003, 09:35 AM
  4. memory allocation
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 06-09-2002, 01:23 PM
  5. Memory allocation
    By Leiken in forum C++ Programming
    Replies: 5
    Last Post: 02-22-2002, 04:32 PM

Tags for this Thread