• 0

[C++] Heap Vs Stack?


Question

When you create any variables statically, they are allocated on the stack? eg: int someInteger = 5;

When you create any variables dynamically, they are allocated on the heap? eg: int someInteger = new int(5);

Q1) Now, these two memory blocks are at OPPOSITE ends of memory aren't they?

Q2) Is it possible that they could cross over?

Q3) Does the OS prevent this from happening?

Q4) It doesn't happen in Java because everything is a "pointer" (reference to be strictly correct?) isn't it? So everything's on the heap? Nah, think I got that assumption wrong...?!

As a side thing, I'm confused about this in C++...

int myArray[100]; ?//array of 100 integers
int* myArray[100]; //array of 100 integer-pointers
int *myArray[100]; //a pointer to an array of 100 integers, but isn't an array essentially a pointer anyway in C++?

Q5) How do I go abouts accessing the memory locations in the 3rd scenario? I just get segmentation faults if I try to say make myArray[0] = 0:no:: Unless, Ahhh, the 3rd scenario is actually just an array of integer-pointers? Because in C++, these mean the same:

int* someInteger = 5;
int * someInteger = 5;
int *someInteger = 5;

Link to comment
Share on other sites

20 answers to this question

Recommended Posts

  • 0
When you create any variables statically, they are allocated on the stack? eg: int someInteger = 5;
Yes. Variables are allocated statically usually when you know exactly how much data you'll be storing before runtime.
When you create any variables dynamically, they are allocated on the heap? eg: int someInteger = new int(5);

Yes. The heap is usually used when you will determine the amount of data required at runtime.

Q1) Now, these two memory blocks are at OPPOSITE ends of memory aren't they?
That's pretty platform-dependent, and irrelevent anyway.
Q2) Is it possible that they could cross over?

No, the operating system makes sure one program doesn't access another's memory without permission.

Q3) Does the OS prevent this from happening?
Yes, see Q2
Q4) It doesn't happen in Java because everything is a "pointer" (reference to be strictly correct?) isn't it? So everything's on the heap? Nah, think I got that assumption wrong...?!

Not everything is on the heap, only reference objects like classes. I believe int, long, etc. are allocated on the stack (that's the way it's in c#,) but don't quote me on that.

Q5) How do I go abouts accessing the memory locations in the 3rd scenario? I just get segmentation faults if I try to say make myArray[0]= 0 no.gif Unless, Ahhh, the 3rd scenario is actually just an array of integer-pointers? Because in C++, these mean the same:

In the 3rd scenario, you have an array of pointers to int's, so in essence, a pointer to a pointer.

To access the value in an array like that, you would have to dereference twice. Since the Array accessors ([]) act just like dereferencing, you only need to do it once more:

*myArray[0] = 0

The reason you get a segfault with

myArray[0] = 0

is because you're setting the pointer at offset 0 of myArray to a NULL pointer (0).

I hope that clears some things up. :)

bwx

Link to comment
Share on other sites

  • 0

Howdy, thanks for clearing those Q's up :)

Reply to Q5) Hmm, that's what I thought... but when I do this:

int main() {
  int *myArray[100];
  *myArray[0] = 5;
  cout << *myArray[0] << endl;
  return 0;
}

I get a seg fault :( How come?

New Q6) How about in C++ how you can just randomly (eg. going off ends of the arrays) get stuck into overwriting memory from other things currently running on the OS or other pieces of memory!? Nothing to prevent you doing that huh? :(

Link to comment
Share on other sites

  • 0

You have an array of pointers. You're trying to dereference an invalid pointer. That causes the seg fault.

myArray is an array of pointers; not an array of integers.

myArray[x] gives you a pointer; not an integer. This pointer is currently invalid.

*myArray[x] will blow up because you tried to dereference myArray[x], which as I mentioned before is a pointer.

Link to comment
Share on other sites

  • 0

Ah, yeah. Forgot to tell you that you have to initialize the array of pointers. In its current state, they are just an array of dangling pointers (i.e. they could point anywhere.) What you need to do is something like:

int *myArray[100];
int x = 0;
while (x<100)
{
     myArray[x] = new int;
      ++x;
}
// use myArray
x=0;
while (x<100)
{
     delete myArray[x];
     ++x;
}

New Q6) How about in C++ how you can just randomly (eg. going off ends of the arrays) get stuck into overwriting memory from other things currently running on the OS or other pieces of memory!? Nothing to prevent you doing that huh? sad.gif

If a program tries to access another program's memory space, the operating system ends the offending program.

Hope that helps,

bwx

Link to comment
Share on other sites

  • 0

Thanks, got it. Just to confirm, the following lines are exactly the same aren't they?

int* myArray[100];
int *myArray[100];

Link to comment
Share on other sites

  • 0
Am I an idiot because I took a year of C++ and still done know what object-oriented programming means?

Not really since you have most likely used the OO aspects of C++ during your class, just haven't realized it.

I would explain what Object Oriented Programming is, but Wikipedia can do a way better job.

Here you go: http://en.wikipedia.org/wiki/Object-oriented_programming

Hope that helps,

bwx

Link to comment
Share on other sites

  • 0

THERE IS SO MUCH GOD DAMN READING TO DO IF YOU WANT TO BE A GOOD C++ PROGRAMMER, I SWEAR THE F-ING GOD!@@%@%$!%!

And it's all...so...boring... why do people do it!?

Link to comment
Share on other sites

  • 0
THERE IS SO MUCH GOD DAMN READING TO DO IF YOU WANT TO BE A GOOD C++ PROGRAMMER, I SWEAR THE F-ING GOD!@@%@%$!%!

And it's all...so...boring... why do people do it!?

Haha, I think the key is persistency and just working your way up from the bottom :laugh: Take it bit by bit/course by course... I found programming a god damn chore at first, but now I find it quite interesting. Don't know how that happened!! :woot:

Link to comment
Share on other sites

  • 0

int myArray[100] /*array containing 100 int*/

int* myArray[100]; /*array containing 100 pointers, each pointing at an int*/

int *myArray[100]; /*same as above*/

also when u use [int *a=new int();], u r not specifiying any address to create the integer. so it obviously becomes the job of the OS to do that. Also u will notice that if u do not delete ur pointers [delete a;], pretty soon u run out of space in ram for new variables and ur program crashes.

so if u use pointers, always delete them unless using .NET that maintains its own garbage collection. Still it is a good practice to delete pointers u dont use,

Link to comment
Share on other sites

  • 0

in other words, you can't explicitly make a pointer to an array ---> since one is made implicitly anyway? yep? :ninja:

by the way, i've seen stuff like: references TO pointers... int*&... in what cases/scenarios would you need such coding?? ta.

Link to comment
Share on other sites

  • 0

u can say an array is a pointer to a set of objects, if u pass a whole array as an argument to a function, u have to handle it as pointer when handling it within the function

by the way, i've seen stuff like: references TO pointers... int*&[\quote]

i am not exactly sure wat u mean. do u mean something like

char **group; ?? that would mean that the group pointer is a set of pointers intself, each of which has to be properly initialized though using new

Link to comment
Share on other sites

  • 0
by the way, i've seen stuff like: references TO pointers... int*&... in what cases/scenarios would you need such coding??

It's just useful if you don't want the function implementation to keep using the dereferencing operator (i.e. *). For example, AllocateResource()'s implementation below doesn't use any pointer dereferencing.

bool AllocateResource( char*& pBuffer, size_t nSize )
{
    if( pBuffer != NULL || nSize == 0 )
        return false;

    try
    {
        pBuffer = new char[nSize];
    }
    catch( std::bad_alloc& e )
    {
        return false;
    }

    return true;
}

int main()
{
    char* MyData = NULL;
    if( AllocateResource( MyData, 50 ) )
        return 0;
    else
        return -1;
}

Link to comment
Share on other sites

  • 0
by the way, i've seen stuff like: references TO pointers... int*&... in what cases/scenarios would you need such coding?? ta.

A reference to a pointer is needed when you want to modify the actual value of the pointer (the address stored in the pointer variable.) It's vital here to understand that a pointer is a variable too; it holds the address of something else. When you pass a pointer to a function, you are passing it by value, meaning you are only passing the address of the pointer; you can't modify the address stored in the pointer you are passing. For example if you want to zero out a pointer when you are done using it, you can't just pass in the pointer, you need to pass in the pointer variable as well.

template <typename T> void zap (T*& p)
{
     delete p;
     p = 0;
}

Whereas if you had done:

template <typename T> void zap (T* p)
{
     delete p;
     p = 0;
}

you would be modifying the local pointer variable in the function instead of having it effect the one outside.

There are other ways to doing this (passing in a pointer to the pointer, but this is generally what it is used for.)

I hope that helps,

bwx

Link to comment
Share on other sites

  • 0

Oh cheers, I get it, it's essentially the same thing to do with scope and modification when passing in other variables as references in function parameters. cool.

hey what is the type size_t you use up there oogle?! you use it just like it is an int?

Link to comment
Share on other sites

  • 0
hey what is the type size_t you use up there oogle?! you use it just like it is an int?

size_t is an unsigned integer type used to hold the size of things. It's usually declared as

typedef unsigned int size_t;

even though some compilers change it into a 64-bit unsigned integer.

bwx

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.