Sign in to follow this  
Followers 0
JohnOne

C++ basic question (heap - stack)

9 posts in this topic

#1 ·  Posted (edited)

I've been reading up on the difference between the heap and the stack, which is where

my question spawns from.

I'm pretty sure I get it, but here's what I think I know.

heap is the rest of your computers memory which has not been allocated to the OS

or some app or another, including the running app.

If you create a variable with new keyword, it's created on the heap.

If you create a variable without the keyword it is created on the stack.

My question is, where is the pointer created, which is used to access a variable created

on the heap?

int * pNum = new int(); // pNum is a pointer to an int created on the heap (I think)

Where does the actuall pointer pNum reside?

EDIT:

I suppose it would have to be created on the stack else the user/caller would

not know where to find the new int on the heap.

I'm often wrong though.

Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites



Close. About as close as you really need to be in order to program, any more specific and you begin to enter the territory of implementation dependant stuff, and the whole idea of languages like C++ is that you don't need to worry about that "stuff".

A heap is a block of memory. You shouldn't think of the heap as being system wide, more like individual heaps allocated to processes. A process has its system provided heap.

Local variables are on the stack. There is a register (ebp) that is used to define where the stack frame for the current function is. Since the number of locals is always known, your int* value is always at a specified position relative to ebp. I really recommend compiling the code, setting a breakpoint then looking at the disassembly. Even if you don't understand assembler you'll get the rough gist of what is going on. Something like:

int* pNum;

    pNum = new int();

Would be something like:

push ebp
mov ebp,esp
add esp,4                  ; int* pNum;
push 4
call malloc                  ; new int()
mov [ebp+4],eax        ; pNum =
1 person likes this

Share this post


Link to post
Share on other sites

If you create a variable with new keyword, it's created on the heap.

No, you create a reference / pointer on the stack, whoose value is the pointer to a new object, which is allocated on the heap.

If you create a variable without the keyword it is created on the stack.

Goes for both cases.

My question is, where is the pointer created, which is used to access a variable created

on the heap?

int * pNum = new int(); // pNum is a pointer to an int created on the heap (I think)

Where does the actuall pointer pNum reside?

I guess you figured this out by now, but it's on the stack.

heap is the rest of your computers memory which has not been allocated to the OS

or some app or another, including the running app.

Not quite, the heap of the program is a kinda like a memory-rental store. If you need memory extra memory, a large amount of memory (can create stack overflow on the stack) or a variable amount of memory, you go ask the store to rent some. If they have some available in your size, you borrow it, but you have to give it back.

In practice, it's usually implemented as an expandable, indexed buffer, that allows you to do what i said earlier. If the heap is getting near empty, it asks the OS for some more virtual memory in form of pages (-> virtualalloc on msdn), therefore it's process specific. Think of it as an array you can redim.

A cool way to really understand it is to write your own :)

1 person likes this

Ever wanted to call functions in another process? ProcessCall UDFConsole stuff: Console UDFC Preprocessor for AutoIt OMG

Share this post


Link to post
Share on other sites

While its most convenient to think of local variables as stored on the stack, there's no guarantees that a variable will be stored there, or even created. Compiler optimizations can completely optimize out a variable, or place it in a processor register. Usually, the only way to be sure that it's going to land on the stack is to somewhere take the address of that variable. But even then, optimizations could get rid of it.

Also, anything declared 'static' inside a function, or any variables outside of a function won't be stored on the stack. They'll be stored in the data segment, which is loaded up along with the executable.

Heaps are resources that are allocated by the runtime library, or some overloaded functions. Heaps don't have to exist in memory, nor do they have to be allocated using specific structures. As others have pointed out, typically the amount of memory available to the O/S doesn't limit the amount of memory you can allocate for each process.

But thats all irrelevant if your focus is on what is keeping track of those resources. Any pointer to a resource must be known by the running code, so if something is allocated, there's a guarantee that something 'concrete' locally will contain a pointer to it (whether its the stack, a register, or a place in the data segment).

P.S. Since you're compiling using VC++2010, I suggest learning Modern C++ style. shared_ptr's, weak_ptr's, and unique_ptrs are your friend.

2 people like this

Share this post


Link to post
Share on other sites

Thank you kindly for the info and advice gentleman.

Main reason for this was from reading tutorials and articles about

pieces of code, heap and stack kept popping up, and I felt I needed to know

at least basically, what they are.

Cheers.


AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites
What is differences between autoit and C++???

Life is like a coin. You can spend it Anyway as you wish and for your kind information. "you can spend it only once."

Share this post


Link to post
Share on other sites

I can't see how your question is related to this topic? If you read wikipedia about the two then it should become a little clearer.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM .

Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.

Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.

More about......Stack and Heap

Warner

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0