new and delete/ heap and stack

Pages: 12
first of what exactly is stack versus heap memory? I was reading something that said basically std::vector is using it call new on its constructor and delete on its destructor. Of course why allocate on the heap in ther first place? Why not just have it auto done for you?

EDIT: from what it looks like, it looks like it dis-obeys normal scope rules, created at start of a function, ends at end of function. Why would you want something to live longer?


1
2
3
4
5
6
7
8
9
10
11
12
13
class Test{
	public:
		Test(){
			int var = new assign();
		}
		~Test(){
			delete var;
		}
		int assign(){
			return 1;
		}
		
};
Last edited on
metulburr wrote:
I was reading something that said basically std::vector is using it call new on its constructor and delete on its destructor. Of course why allocate on the heap in ther first place? Why not just have it auto done for you?

How would you have it auto done for you? The size of an object is fixed. It cannot change. std::vector doesn't know how large array it is going to need, so it uses new to allocate the array of the size it wants. If it later needs a bigger array it allocates a new array and copies the elements from the old array to the new array before it deletes the old array.

metulburr wrote:
from what it looks like, it looks like it dis-obeys normal scope rules, created at start of a function, ends at end of function. Why would you want something to live longer?

std::vector creates the array in the constructor (or some other function) and deletes it in the destructor. That is two different functions. It would be useless if std::vector couldn't remember the elements you insert into it.
How would you have it auto done for you?

i mean not even use the new keyword
first of what exactly is stack versus heap memory?

read how each works and you will know

i mean not even use the new keyword

and how do you plan on doing this?
read how each works and you will know

all it says is one is stack and one is heap. That doesnt explain anything to a beginner.

and how do you plan on doing this?
1
2
3
int main(){
	int a = 0;
}

there. i didnt use the new keyword.

and what does it matter these days. I have 20GB of RAM. I could waste space and still execute a program effeciently
Last edited on
If you know no difference between heap and stack (ang google is full of images), and you dont want to use new, you can create 10GB array and play with it LOL.

I mean, you cant be serious with this quote
I have 20GB of RAM. I could waste space and still execute a program effeciently
. If thats you argument against using new, you should use some very high level languages (java, c#, etc) and dont think about heap or stack and dont use pointers at all.

How can you even question RAM architecture without even reading why it is made how it is.

1
2
3
int main(){
	int a = 0;
}

And how will you allocate memory when you dont know array size in compile time?

In most cases stack is FIFO structure. If you place your variable on it and some other variable will be pushed after it, you wont be able to use it. With heap, you have access to allocated memory all the time.
You guys complain about making sure to delete an array that has maybe 1KB of space. On RAM with 20GB what does it matter if you forget to delete a small number like that?

i dont understand why one wouldnt just use stack all the time and not use heap.

if memory on the heap is suppose to be out of scope why would one function not know the other function that created memory on the heap?
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

void test(){
	std::cout << a;
}

int main(){
	int *a;
	a = new int;
	
	*a = 10;
        test();
}

1
2
3
4
5
test2.cpp: In function ‘void test()’:
test2.cpp:5:15: error: ‘a’ was not declared in this scope
  std::cout << a;
               ^

so obviously test() needs to be passed a as a parameter, what is the point of putting it on the heap then?
Last edited on
closed account (Dy7SLyTq)
putting it on the heap isnt to make it global. the most popular thing ive seen is for using it for dynamic char arrays. however i dont know why you expected a to be global. that would lead to bugs. what if you did
1
2
3
4
5
void test()
{
     int a = 1;
     std::cout<< a;
}


which a is it supposed to pick. there are already enough problems with global variables
i dont understand why one wouldnt just use stack all the time and not use heap.

then how would you do this with stack only?:
1
2
3
4
5
6
7
8
9
10
int main()
{
	unsigned size;
	cin >> size; // enter array size

	arr = new int(size);
	delete arr;

	return 0;
}
Last edited on
It's rather easy: use the stack as long as you can.

You will see that when the program exceeds a certain complexity, there's no other way then using dynamic memory (or indirectly container)
In your example a is allocated on the stack and follows the same rules as any stack-allocated object. It is the object that a points to that is allocated on the heap.
tath wrote:
then how would you do this with stack only?:
1
2
3
4
5
6
7
8
9
10
int main()
{
	unsigned size;
	cin >> size; // enter array size

	arr = new int(size);
	delete arr;

	return 0;
}


to me that looks the same as on the stack except explicitly init and deleting it. The same looks to me like:
1
2
3
4
5
int main(){
    int size;
    std::cin >> size;
    int arr[size];
}

and this way you dont have to explicitly delete it, its done for you at the end of the function.


@coder777 @Peter87
so could you use std::vector or some other container to avoid using new/delete?
Last edited on
so could you use std::vector or some other container to avoid using new/delete?

But the vector will still be allocated on the stack. If you need to manage the persistence of that vector manually, so that it persists outside the scope it's declared in, then you'd need to dynamically allocate the vector anyway.
ok i think i am going to skip heap/stack for awhile because I do not understand the concept.

thanks
It's quite simple why you would not use stack-only or heap-only.

1. Heap-only is not possible, you need to store AT THE VERY LEAST a single pointer on the stack.
2. Stack-only will only work for very small programs (who require a FIXED amount of memory and whose memory request is under a certain limit, usually 64KB minus the memory used by the callstack, which shouldn't be above 1KB).

So, if you have 20GB of RAM, you would be using heap memory.

Also:

- Always free (delete) your memory.
Even if you do have 20GB of RAM (make your lie worth it and take us a picture, it's not something I see everyday), not everyone else does.
My sister still runs on a 256mb machine using Windows XP SP2.
If you were to leak memory, her PC would likely block.
So please be respectful to your sisters.

- Leaking memory is lying to your operating system (And if you hate your operating system, change it, don't leak memory).
Your operating system always waits you to "physically" release the memory once you're done with it, so it can use that memory for something else.

- Memory is something important, and is easy to waste.
You'll learn it quite fast, memory must not be wasted for useless things.
Always try to cache what you can, if you cache your things in the optimal way you will see the program running very good.
It will "run faster", but make sure to free what you don't use in the cache (eventually put a timer running in a thread, checking for the last access of the cache and deleting that part of the cache which hasn't been used in the last two minutes).

[Edit]

- Leaking can result in more leaking
1
2
3
4
{
    std::vector<int> * myVector = new std::vector<int>;
    myVector->resize(5000);
}


What happens here?
You're not just leaking sizeof(std::vector<int>) bytes.
You're also leaking sizeof(int)*5000 (or more, depending on implementation) bytes.

Now, for that picture :D
Last edited on
closed account (Dy7SLyTq)
20GB of RAM (make your lie worth it and take us a picture, it's not something I see everyday)

i agree; the highest ive seen is 16 (not to say your lying, just that its not as common as say 4 gigs). my friend has this like high end gaming desktop with a terabyte hard drive (it might have even been solid state), i5 processor, liquid cooling system, and the 16 gigs of ram. needless to say i was jealous

edit: whats the advantage to declaring vector new? i thought it was dynamic already
Last edited on
With 20GB of RAM you're assuming that all C++ development is for modern computers.

The PS3 has 256MB of RAM and 256MB of VRAM. Other devices much less.
Last edited on
@DTSCode:
The vector's CONTENTS are dynamically allocated.
But the vector itself is allocated by you.

1
2
3
4
std::vector<int> i;
// sizeof(std::vector<int>) bytes used on the stack
std::vector<int> * pi;
// sizeof(std::vector<int>*) bytes used on the stack, usually same as sizeof(void*) 


Just asked my progamer mate.
His specs are on this line:

Corsair, 16GB of Ram
Intel i5 3570k @ 4.4ghz
SSD: 128gb
Asus HD6950

Powered with 750W.

It's quite hard to assume every PC user has these specs.
Cheap users (like me) barely use the 400W of their pw supply.
I also try to assume no one has my same specs, and I'm on a 4GB/2Ghz/HDD-powered PC.
Last edited on
closed account (Dy7SLyTq)
alright that makes sense. and why does one do that? to make the size smaller? (nvr mnd:
What happens here?
You're not just leaking sizeof(std::vector<int>) bytes.
You're also leaking sizeof(int)*5000 (or more, depending on implementation) bytes.
) so im not gonna guess anymore because i dont see the point ( i realize how that sounds but im not trying to argue there is no point. im asking because i see no point)
Think of it like this.

1
2
3
4
5
6
7
8
9
10
11
struct MyComplexStruct {
    std::vector<int> myVector;
    MyComplexStruct() { myVector.resize(5000); }
};

int main()
{
    MyComplexStruct * mystruct = new MyComplexStruct;
    return 0;
}


It's just an example.
You forget to delete mystruct?
myVector will not be deleted either.
Neither its content.

Leak brings leak.
Also, this could be called "heap abuse", I remind LB calling it something like that ("Unless you NEED it on the heap, use it on the stack")
Last edited on
Pages: 12