new and delete for pointers?

Started by
16 comments, last by SirKnight 17 years, 6 months ago
When do you use new and delete for pointers in C++? I just finished the section on pointers, but then it starts using new and delete to add or remove space from the heap. Before it wasn't using these commands with pointers. It doesn't seem to specify when and when not to do this. Thanks
Advertisement
You use them whenever you need dynamic memory allocation/deallocation. Static memory already manages things for you via a stack, but there are a couple of restriction: sizes of things must be known at compile time and the stack itself has a limit. There are situations when you don't know sizes of things in advance. For example, if there is a file you want to load into memory, you can do one of the following things:

//Static memory#define MAX_FILE_SIZE (1024*1024)unsigned char buffer[MAX_FILE_SIZE]; //The static buffer for reading the filefread(buffer ...); //What happens if the file is bigger than 1MB? Oops!... Do Something with the buffer ...return true; //The memory for the buffer will be automatically released here//Dynamic memoryint fileSize = FileSize(file); //Calculate the file's size first.unsigned char* buffer = new unsigned char[fileSize]; //Allocate exactly the amount of space we need.fread(buffer, ...); //No worries here, it won't overflow the buffer.... Do something with the buffer ...delete [] buffer; //Release the dynamic memory.buffer = NULL; //Set the pointer to null, as a precaution... Do something else that doesn't involve the buffer ...return true; //The memory for the buffer is not automatically released, so that's why we called delete [].


As you can see, in the static memory example we just pulled a max file size number out of out $%^ and hoped that we will never have to deal with files larger than that. There is also a danger of overflowing the stack when you have too many static variables like that.

Dynamic memory allocation is much more flexible than that, it allows specifying sizes at runtime and there is no built-in limit to the size you want to allocate. There is a catch, however: dynamic memory must be carefully managed using pointers and new/delete operators.
deathkrushPS3/Xbox360 Graphics Programmer, Mass Media.Completed Projects: Stuntman Ignition (PS3), Saints Row 2 (PS3), Darksiders(PS3, 360)
I see why you would use new and delete, but doesn't the pointer already take up dynamic memory when you use it? Even if you don't request a space on the heap? Thats why you use a pointer. So you can use dynamic memory instead of static memory.
I guess what I'm getting at is when you use pointers should you always use new to allocate a space for the memory address or are there times when you just declare the pointer and use it without allocating a space in memory?
you dont need to allocate space in something like this:

int x=0;int *y=0;y = &x*y = 5;cout << x; //prints 5

If you know the size you want the pointer to be, and that size is constant, then sure, define without new and delete. For the file size example, new and delete are needed because the file size can vary.
bi-FreeSoftware
Quote:I see why you would use new and delete, but doesn't the pointer already take up dynamic memory when you use it? Even if you don't request a space on the heap?

No, not at all. You always need to remember what a pointer actually does, it points somewhere in memory. Initially a pointer doesn't point to anything you can use though, therefore you need to make it point at some memory which you have the permission to modify. You can either point it somewhere on the stack by taking the address of a stack variable, of course this means that if you write something to the pointer's location, then the stack variable will be overwritten. Sometimes you don't have a stack variable you want to waste, or you might not know the exact size you need until runtime. Stack variables size is always known at compile time. So we need to get an address to some memory we can use.

Somewhere in the OS there is a memory manager which have a list of all the free memory, so you need to point to some of that, you don't know where it's though, and you don't know how to tell the manager that the memory isn't free anymore. This is what new is for, when you call new we tell the manager we would like a chunk of memory, it then chooses some of the free memory, marks it as used and send us the address. Since we only have limited free memory, the memory manager needs to reuse the memory, so when we are done with some memory we tell it that we are done by calling delete. Then the memory manager marks that memory as free once more.

For completeness I will mention, that on some systems, where you know you are the only application which runs, you can often explicitely assign pointer values. So you might do, int* a = 0x0400A. This is sometimes used by programmers on these platforms to avoid the overhead new and delete has. You most likely doesn't have access to such a platform though (Gameboy, MS-DOS, etc.), so ignore it, I just thought I'd mention it.
When you declare a pointer, it is a null pointer pointing at nothing.
When you use "new", it returns a pointer to the allocated space in the heap, and your pointer will point to something you can use from there on.

you don't have to use the "new" if there is another pointer already, in which case you can do something like

pPointer1 = pPointer2;

and the pointer1 will be pointing to the same thing in the heap as the pointer2.
Thanks for your help. With every chaper I read I realize I don't know enough about memory and how important it is in C++. I guess I better look for a book on computer memory and how it works.
Pointers do also take up some stack memory, but just 4 bytes (enough to point to a location in memory, which is 4 bytes on many compilers/processors).

Sometimes pointeres are helpfull when you need one object to be able to look at another. Say, you've got a Map object (if you haven't covered classes yet, just think of them as a physical object for now) which contains a number of Units. Each Unit may need to know which Map it is part of. You could use a pointer for this, even though at no point does the Unit allocate memory for the Map, neither on the stack nor the heap.

References can do alot of what pointers do, and are safer and easier. Use them once you learn them and when possible.

This topic is closed to new replies.

Advertisement