Computer Science Canada

Memory Allocation

Author:  Cancer Sol [ Thu Apr 04, 2013 4:45 pm ]
Post subject:  Memory Allocation

Today, I was learning about Memory Allocation, using new and delete.
However,when I made a test program, the value wasn't what I wanted it to be.
c++:

#include <iostream>
using namespace std;

int main()
{
    int number;
    cin >> number;
    int *ptr_number = new int[number];//I tried to assign *ptr_numbers the value of number
    cout << *ptr_number;//The output wasn't what I entered though
}

What did I do wrong there?

Author:  Panphobia [ Thu Apr 04, 2013 5:03 pm ]
Post subject:  RE:Memory Allocation

You just initialized a new array of integers of size number, you did not store the value of number in it.

Author:  Cancer Sol [ Thu Apr 04, 2013 5:43 pm ]
Post subject:  Re: RE:Memory Allocation

Panphobia @ 4/4/2013, 5:03 pm wrote:
You just initialized a new array of integers of size number, you did not store the value of number in it.

Oh.. the example in the book is kinda confusing then :/

How do I assign it the value of what I input then?

Author:  Panphobia [ Thu Apr 04, 2013 5:50 pm ]
Post subject:  RE:Memory Allocation

use ( ) instead of [ ] and everything else the same

Author:  Cancer Sol [ Thu Apr 04, 2013 7:53 pm ]
Post subject:  Re: RE:Memory Allocation

Panphobia @ 4/4/2013, 5:50 pm wrote:
use ( ) instead of [ ] and everything else the same

Thanks, it works now Very Happy
What if I left it like that so it's an array, how do I assign it a value? Let's just say we'll assign it to [0]

Author:  Panphobia [ Thu Apr 04, 2013 8:31 pm ]
Post subject:  RE:Memory Allocation

you can use a for loop from 0 to the array length and add values to all indexes of the array

Author:  Cancer Sol [ Fri Apr 05, 2013 12:49 am ]
Post subject:  Re: Memory Allocation

Oh wait, actually I think I know how to do it now.
Still not too sure, but I'll just try it out tomorrow.

Author:  wtd [ Fri Apr 05, 2013 1:08 am ]
Post subject:  Re: Memory Allocation

Quick tip:

code:
#include <iostream>
#include <algorithm>

int main()
{
        int *foo = new int[10];

        std::fill(foo, foo + 10, 0);

        for (int i = 0; i < 10; i++)
        {
                std::cout << foo[i] << std::endl;
        }

        return 0;
}

Author:  Insectoid [ Fri Apr 05, 2013 4:35 pm ]
Post subject:  Re: Memory Allocation

wtd @ Fri Apr 05, 2013 1:08 am wrote:
Quick tip:

code:
#include <iostream>
#include <algorithm>

int main()
{
        int *foo = new int[10];

        std::fill(foo, foo + 10, 0);

        for (int i = 0; i < 10; i++)
        {
                std::cout << foo[i] << std::endl;
        }

        return 0;
}


Why didn't they ever teach me this in school? So many for loops I didn't have to write!

Author:  wtd [ Fri Apr 05, 2013 4:43 pm ]
Post subject:  RE:Memory Allocation

The STL (Standard Template Library) is not for the faint of heart. It makes deep use of templates, which are tricky, and do not result in pleasant error messages.

Teachers avoid it because C++ is complicated enough to teach as it is, but also because many employers who hire programmers to work in C++ also avoid it. To some extent that situation is a chicken and egg problem.

Author:  Cancer Sol [ Fri Apr 05, 2013 4:48 pm ]
Post subject:  Re: Memory Allocation

wtd @ 4/5/2013, 1:08 am wrote:
Quick tip:

code:
#include <iostream>
#include <algorithm>

int main()
{
        int *foo = new int[10];

        std::fill(foo, foo + 10, 0);

        for (int i = 0; i < 10; i++)
        {
                std::cout << foo[i] << std::endl;
        }

        return 0;
}

I saw that in my ebook already, thanks anyways Razz
The example I saw didn't say it was for arrays, so I was kind of confused.

Btw, is there a way to delete a non-integer pointer? Since I can't do something like this:
c++:

POINT *cursorpos = new POINT[amount];

since it's not an enum or integer... is it even possible to get memory from the free store for the structure POINT?
Edit: Nevermind, reread it.. what does this do?
code:

std::fill(foo, foo + 10, 0);

and what does the algorithm header file allow me to do?

Author:  nullptr [ Fri Apr 05, 2013 5:01 pm ]
Post subject:  Re: Memory Allocation

Including <algorithm> lets you use a bunch of useful, generalized functions, like swapping, sorting, searching, etc. You can find a description of all these algorithms (including fill) at http://www.cplusplus.com/reference/algorithm/

Author:  Cancer Sol [ Fri Apr 05, 2013 5:36 pm ]
Post subject:  Re: Memory Allocation

I'm so stupid, I could've just googled that -_-
Thanks Razz

Author:  Cancer Sol [ Fri Apr 05, 2013 5:40 pm ]
Post subject:  Re: RE:Memory Allocation

wtd @ 4/5/2013, 4:43 pm wrote:
The STL (Standard Template Library) is not for the faint of heart. It makes deep use of templates, which are tricky, and do not result in pleasant error messages.

Teachers avoid it because C++ is complicated enough to teach as it is, but also because many employers who hire programmers to work in C++ also avoid it. To some extent that situation is a chicken and egg problem.

What do you mean by The STL is not for the faint of heart? like it's just really hard?
Should I even bother with it then?

Author:  wtd [ Fri Apr 05, 2013 5:50 pm ]
Post subject:  RE:Memory Allocation

The STL requires a reasonably deep knowledge of C++. Of course, trying to figure it out can be a good incentive to investigate the more interesting concepts in C++.

Author:  Cancer Sol [ Fri Apr 05, 2013 6:00 pm ]
Post subject:  Re: RE:Memory Allocation

wtd @ 4/5/2013, 5:50 pm wrote:
The STL requires a reasonably deep knowledge of C++. Of course, trying to figure it out can be a good incentive to investigate the more interesting concepts in C++.

Alright thanks Smile
So, is it possible to get the memory the size of POINT from the free store? Is it possible to even get memory from the free store
if it's not an integer or enum?

Author:  Insectoid [ Fri Apr 05, 2013 6:40 pm ]
Post subject:  RE:Memory Allocation

Dunno how it's done in c++, but in C, the sizeof() function will return the size of the type passed to it. sizeof(int) returns the size of an int. sizeof (POINT) will return the size of POINT.

Author:  Cancer Sol [ Fri Apr 05, 2013 6:44 pm ]
Post subject:  Re: RE:Memory Allocation

Insectoid @ 4/5/2013, 6:40 pm wrote:
Dunno how it's done in c++, but in C, the sizeof() function will return the size of the type passed to it. sizeof(int) returns the size of an int. sizeof (POINT) will return the size of POINT.

Well, that wasn't what I was really wondering, although that might help me in the future.
Here's an example for an integer:
code:

int *example = new int;

Which I tried this:
code:

POINT *example = new POINT;

but I found out that New and Delete only works with integers and enums.
How do I request for more memory and delete the pointer with POINT?

Author:  Insectoid [ Fri Apr 05, 2013 6:50 pm ]
Post subject:  RE:Memory Allocation

We could do things the C way again, I suppose.

code:
Point* example = (POINT*) malloc (sizeof (POINT));


malloc is a C function that directly allocates a block of memory of a given size.

Author:  Cancer Sol [ Fri Apr 05, 2013 7:13 pm ]
Post subject:  Re: RE:Memory Allocation

Insectoid @ 4/5/2013, 6:50 pm wrote:
We could do things the C way again, I suppose.

code:
Point* example = (POINT*) malloc (sizeof (POINT));


malloc is a C function that directly allocates a block of memory of a given size.

I guess I can try that...
Does C++ not have its own function for it though?

Author:  DemonWasp [ Fri Apr 05, 2013 7:18 pm ]
Post subject:  RE:Memory Allocation

In C++, new and delete DO work with things other than int and enum: they work with pretty well everything!

Assuming that POINT is declared...
code:
POINT *example = new POINT(); // needs the brackets!


Later...
code:
delete example;


You can even use new to create arrays of whatever you want:
code:

POINT **ex_arr = new POINT[size];  // creates an array of (size) pointers to POINT objects on the heap
for ( int i = 0; i < size; ++i ) {
    ex_arr[i] = new POINT();   // constructs a new POINT object on the heap and puts the pointer to it into position i of ex_arr
}


Later...
code:
delete [] ex_arr;  // the square brackets are very important, because they tell the compiler that you want to delete ex_arr AND all of its contents

Author:  Cancer Sol [ Fri Apr 05, 2013 9:33 pm ]
Post subject:  Re: RE:Memory Allocation

DemonWasp @ 4/5/2013, 7:18 pm wrote:
In C++, new and delete DO work with things other than int and enum: they work with pretty well everything!

Assuming that POINT is declared...
code:
POINT *example = new POINT(); // needs the brackets!


Later...
code:
delete example;


You can even use new to create arrays of whatever you want:
code:

POINT **ex_arr = new POINT[size];  // creates an array of (size) pointers to POINT objects on the heap
for ( int i = 0; i < size; ++i ) {
    ex_arr[i] = new POINT();   // constructs a new POINT object on the heap and puts the pointer to it into position i of ex_arr
}


Later...
code:
delete [] ex_arr;  // the square brackets are very important, because they tell the compiler that you want to delete ex_arr AND all of its contents

Well, I'm using GNU GCC compiler, and it said that that new can only be used with enums and int, idk why.
I'll try it again, but I think my error might be that I'm missing a * for the pointer array.
I thought it was just one pointer like this:
c++:

POINT *ex_arr = new POINT [size];

What do you mean by heap though?

Author:  DemonWasp [ Fri Apr 05, 2013 10:22 pm ]
Post subject:  RE:Memory Allocation

First, there are two main places you allocate memory in C++ (and in programs in general, though most other languages choose to hide these details): the "stack" and the "heap".

Stack allocation is "cheaper" in terms of time, but may cause scoping problems (you cannot return a stack-allocated object or variable from a function and expect it to still be valid).

Heap allocation (using new or malloc or any of malloc's family) is "more expensive" (only a little bit), but has the advantage that you can allocate something within a function and then return it.

There are a lot of schools of thought on how to use each kind of allocation best. The only obviously-true things seem to be: allocate on the stack when you can, and use the RAII pattern when you can (you *should* be reading about that in your C++ textbook around when it discusses allocating memory for objects or where it talks about destructors; don't worry about it until you get there).

This:
code:
POINT **ex_arr = ...

declares a pointer to a pointer to a POINT object.

This:
code:
POINT *example = ...

declares a pointer to a POINT object.

These correspond to two different ways to lay out the memory you have allocated.

For the example pointer, that can either be a pointer to a single POINT object, or it can be treated like an array of POINT objects. If you allocated example as an array, then you can access a member 'x' of POINT #i with this syntax: example[i].x. All of the POINT objects will be contiguous in RAM, meaning they will be stored side-by-side.

For the ex_arr pointer, that is generally used to mean "an array of pointers to POINT". That means that ex_arr[i] is a *POINT, so if you want member 'x' of POINT #i, use this syntax: ex_arr[i]->x. The POINT objects will probably not be contiguous in RAM, and in fact may be stored all over the place. Because ex_arr is an array of pointers, you can also have ex_arr[i] == nullptr, which may or may not be desirable, depending on what you want to do.


Note: I haven't tested any of the code I posted, so the syntax may not be perfect.

Author:  Cancer Sol [ Sat Apr 06, 2013 4:46 pm ]
Post subject:  Re: RE:Memory Allocation

DemonWasp @ 4/5/2013, 10:22 pm wrote:
First, there are two main places you allocate memory in C++ (and in programs in general, though most other languages choose to hide these details): the "stack" and the "heap".

Stack allocation is "cheaper" in terms of time, but may cause scoping problems (you cannot return a stack-allocated object or variable from a function and expect it to still be valid).

Heap allocation (using new or malloc or any of malloc's family) is "more expensive" (only a little bit), but has the advantage that you can allocate something within a function and then return it.

There are a lot of schools of thought on how to use each kind of allocation best. The only obviously-true things seem to be: allocate on the stack when you can, and use the RAII pattern when you can (you *should* be reading about that in your C++ textbook around when it discusses allocating memory for objects or where it talks about destructors; don't worry about it until you get there).

This:
code:
POINT **ex_arr = ...

declares a pointer to a pointer to a POINT object.

This:
code:
POINT *example = ...

declares a pointer to a POINT object.

These correspond to two different ways to lay out the memory you have allocated.

For the example pointer, that can either be a pointer to a single POINT object, or it can be treated like an array of POINT objects. If you allocated example as an array, then you can access a member 'x' of POINT #i with this syntax: example[i].x. All of the POINT objects will be contiguous in RAM, meaning they will be stored side-by-side.

For the ex_arr pointer, that is generally used to mean "an array of pointers to POINT". That means that ex_arr[i] is a *POINT, so if you want member 'x' of POINT #i, use this syntax: ex_arr[i]->x. The POINT objects will probably not be contiguous in RAM, and in fact may be stored all over the place. Because ex_arr is an array of pointers, you can also have ex_arr[i] == nullptr, which may or may not be desirable, depending on what you want to do.


Note: I haven't tested any of the code I posted, so the syntax may not be perfect.

So if I declare a pointer like this:
c++:

int main()
{
    int amount = 0;
    POINT *ex_array = new POINT [amount];
    *ex_array[amount] = NULL;//Will this work even work?
    GetCursorPos(*ex_array[amount]);
}

Then if I want to request x and/or y, do I use this syntax:
[syntax=cpp"]
*ex_array[amount].x;
//and
*ex_array[amount].y;
[/syntax]
Thanks for helping by the way!

Author:  Panphobia [ Sat Apr 06, 2013 4:56 pm ]
Post subject:  RE:Memory Allocation

That would not work, because when you initialize an array of size n lets say, there are 0 - (n-1) indexes, so giving a value to "array[n]" would give an index out of bounds error, or something like that. Also I am pretty sure an array of size 0 won't hold anything either.

Author:  Cancer Sol [ Sat Apr 06, 2013 7:06 pm ]
Post subject:  Re: Memory Allocation

Can I assign all of *ex_array 's indexes to the value NULL and then assign amount a different value?

Edit: Actually, nvm, I know what you're talking about now. And, I thought an array of size 0 is able to hold data, but I guess I could be wrong.

Author:  Panphobia [ Sat Apr 06, 2013 7:33 pm ]
Post subject:  RE:Memory Allocation

Yes you can assign the values to NULL and then assign different values, but I am pretty sure this is the same thing as assigning the value of 0 to it.

Author:  Insectoid [ Sat Apr 06, 2013 8:33 pm ]
Post subject:  RE:Memory Allocation

If you try to assign an integer the value of NULL, you'll probably get an error. You can set pointers to NULL though, which is actually really useful in certain situations.

Author:  crossley7 [ Sat Apr 06, 2013 9:40 pm ]
Post subject:  RE:Memory Allocation

Assigning the value 0 and NULL are very different things. NULL is something generally used for pointers and can be super useful for things such as linked lists where you need to know you are at the end.

You can also use this assignment for C-strings (and possibly regular strings... not sure of that) since they are technicaly pointers themselves.

0 is a valid value in general and is only invalid if your program defines it to be while NULL by definition is an invalid memory location.

Author:  Cancer Sol [ Sat Apr 06, 2013 9:53 pm ]
Post subject:  Re: RE:Memory Allocation

Insectoid @ 4/6/2013, 8:33 pm wrote:
If you try to assign an integer the value of NULL, you'll probably get an error. You can set pointers to NULL though, which is actually really useful in certain situations.

That's what I was trying to do (in the example).
Wasn't that a pointer that points at a certain address in the free store?
I'm going to have to re-read this stuff to understand it better.

Author:  Panphobia [ Sat Apr 06, 2013 11:21 pm ]
Post subject:  RE:Memory Allocation

crap yea I was thinking of setting an int array to null, because that would be 0 I was not thinking, sorry about that.

Author:  wtd [ Sun Apr 07, 2013 12:10 am ]
Post subject:  RE:Memory Allocation

I am getting the feeling POINT may be better implemented as a class..

Author:  Cancer Sol [ Sun Apr 07, 2013 12:24 pm ]
Post subject:  Re: RE:Memory Allocation

wtd @ 4/7/2013, 12:10 am wrote:
I am getting the feeling POINT may be better implemented as a class..

I don't even know what a Class is xD

Actually, I know what the problem is for my program. It isn't about new and/or delete,
it's just a function I'm not using properly.

Basically, this is what I did:
c++:

int coord=0;
POINT *cursorpos = new POINT [20];
GetCursorPos(*cursorpos[coord]);
coord++;

Which there's something wrong, like I can't use an array within GetCursorPos.
It works when I don't use an array and inside GetCursorPos, I would do this:
c++:

GetCursorPos(&Example);

But I want to store multiple coordinates. How do I do that? I've tried experimenting with it for so long yesterday.

Author:  DemonWasp [ Sun Apr 07, 2013 3:32 pm ]
Post subject:  RE:Memory Allocation

If you want to pass a reference to GetCursorPos (which should be declared as follows):

code:
void GetCursorPos ( POINT &p )


Then you can pass an array element by this:

code:
GetCursorPos ( cursorpos[coord] );


The code you posted tries to dereference 'cursorpos' twice (*cursorpos[coord]), but it only has one level of indirection (basically, one * in its declaration).

If you were passing by pointer rather than reference, then GetCursorPos would look like:

code:
void GetCursorPos ( POINT *p )


And you would pass an array element by this:

code:

// This says "get me the address of the [coord] element of the 'cursorpos' array"
GetCursorPos ( &(cursorpos[coord]) );


or

code:

// This says "get me a pointer to (coord) elements past (cursorpos)."
GetCursorPos ( cursorpos + coord );

Author:  Cancer Sol [ Sun Apr 07, 2013 3:52 pm ]
Post subject:  Re: RE:Memory Allocation

Thanks, D.

The function GetCursorPos() is in the windows.h header file, so I'm going to have to make my own function for that.
I thought the reason why it wouldn't work was because I was using an array, not because I'm using a pointer xD
I wish references knew what NULL is :/

Author:  wtd [ Sun Apr 07, 2013 11:40 pm ]
Post subject:  RE:Memory Allocation

Oh sweet merciful Jebus! The Windows API and you're new enough to programming that you don't know what a class is? Die with dignity.

Author:  Cancer Sol [ Mon Apr 08, 2013 10:48 pm ]
Post subject:  Re: RE:Memory Allocation

wtd @ 4/7/2013, 11:40 pm wrote:
Oh sweet merciful Jebus! The Windows API and you're new enough to programming that you don't know what a class is? Die with dignity.

Aww, don't be so mean D:
I'm learning both at the same time... but if it's a bad thing, I guess I'll just learn all the basics first.

Author:  Sly14Cat [ Wed Apr 10, 2013 6:28 pm ]
Post subject:  RE:Memory Allocation

Yes wtd, don't be so hard on Cancer Sol. This forum is dedicated to people who can create elaborate programs and those who can't declare a variable yet as well as many in between.

Author:  Cancer Sol [ Wed Apr 10, 2013 7:34 pm ]
Post subject:  Re: RE:Memory Allocation

Sly14Cat @ 4/10/2013, 6:28 pm wrote:
Yes wtd, don't be so hard on Cancer Sol. This forum is dedicated to people who can create elaborate programs and those who can't declare a variable yet as well as many in between.

Haha, thanks. It doesn't really matter to me though, I think I should learn more before doing this kind of stuff Razz

Author:  Nathan4102 [ Wed Apr 10, 2013 7:43 pm ]
Post subject:  RE:Memory Allocation

It might be recommended, but I don't think you HAVE to. I've been working with the winAPI in python, and I know nothing about classes, or string manipulation, or array sorting...

Author:  Panphobia [ Wed Apr 10, 2013 7:45 pm ]
Post subject:  RE:Memory Allocation

But it sure helps, and makes things TONS easier.

Author:  Cancer Sol [ Mon Apr 22, 2013 8:35 pm ]
Post subject:  Re: RE:Memory Allocation

Panphobia @ 4/10/2013, 7:45 pm wrote:
But it sure helps, and makes things TONS easier.

If that's the case, I'll just learn it first XD

Just took a break from compsci for about a week... after I played LoL again, I just couldn't stop playing.
Thank god I'm back to programming though.

Author:  Nathan4102 [ Mon Apr 22, 2013 8:37 pm ]
Post subject:  RE:Memory Allocation

I was wondering where you went! Glad ya didn't die or something Wink

Author:  QuantumPhysics [ Tue Apr 23, 2013 7:37 am ]
Post subject:  RE:Memory Allocation

Wait, are we still on about ops question or what?

Author:  Cancer Sol [ Tue Apr 23, 2013 6:30 pm ]
Post subject:  Re: RE:Memory Allocation

QuantumPhysics @ 4/23/2013, 7:37 am wrote:
Wait, are we still on about ops question or what?

What's an ops question?

@Nathan Haha, thanks for caring Wink

Author:  Insectoid [ Tue Apr 23, 2013 6:56 pm ]
Post subject:  RE:Memory Allocation

He meant OP's question. OP stands for Original Poster, aka whoever started this thread (ie you).

Author:  Cancer Sol [ Tue Apr 23, 2013 7:32 pm ]
Post subject:  Re: Memory Allocation

Oh, alright. Thanks!

@QuantamPhysics Nope, I guess not Razz


: