Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pointers and Memory Allocation 3

Status
Not open for further replies.

Watts

Programmer
Jan 18, 2001
80
US
Here is a dozy of a situation, say I declare a pointer to a structure like this:

The structure contains x and y integer values.

Struct* ptr;
ptr->x = 10;
ptr->y = 35;

Is this valid and why don't I need to use the malloc() function to reserve space for this structure and return a memory address? Is the compilier doing some behind the scenes work for me? Where does the data for this structure end up (stack/heap)?
 
I believe it is not valid.

Since this is a C++ forum, I will advise you to use the new and delete operators not the malloc and free functions, as the latter are discouraged in C++.

You must allocate the pointer:

ptr = new Struct;
ptr->x = 10;
ptr->y = 35;

then destroy it when finished:

delete ptr;

I assume x and y are integers, not pointers. If they were pointers, you would be responsible for allocating them as well after the ptr object was initialized;

I believe the memory is allocated to the heap.
 
First of all if you do this you will get a C4700 compiler warning like:
warning C4700: local variable 'ptr' used without having been initialized

Then at run-time you will have an error of type:
the memory could not be "written". - pretty obvious why

If do not get the warning, check your ProjectSettings for warnings.

Hope this helps, s-)

Blessed is he who in the name of justice and good will, shepards the week through the valley of darkness...
 
NOT VALID AT ALL. You definitely need to allocate the memory. When you declare the pointer you get some random memory address. With either a malloc or a new you get a specific memory address that has memory allocated. Without doing this, you will write to the initial memory address and possibly overwrite some important information.

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top