JohnOne Posted November 26, 2012 Share Posted November 26, 2012 (edited) I've been reading up on the difference between the heap and the stack, which is wheremy 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 OSor 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 createdon 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 wouldnot know where to find the new int on the heap.I'm often wrong though. Edited November 27, 2012 by JohnOne AutoIt Absolute Beginners Require a serial Pause Script Video Tutorials by Morthawt ipify Monkey's are, like, natures humans. Link to comment Share on other sites More sharing options...
Mat Posted November 27, 2012 Share Posted November 27, 2012 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 = JohnOne 1 AutoIt Project Listing Link to comment Share on other sites More sharing options...
JohnOne Posted November 27, 2012 Author Share Posted November 27, 2012 Thanks for response Mat. I don't know anything about assembler, but your example does kind of make a bit of sense to me, logically speaking. AutoIt Absolute Beginners Require a serial Pause Script Video Tutorials by Morthawt ipify Monkey's are, like, natures humans. Link to comment Share on other sites More sharing options...
Shaggi Posted November 27, 2012 Share Posted November 27, 2012 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 createdon 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 OSor 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 JohnOne 1 Ever wanted to call functions in another process? ProcessCall UDFConsole stuff: Console UDFC Preprocessor for AutoIt OMG Link to comment Share on other sites More sharing options...
Ascend4nt Posted November 28, 2012 Share Posted November 28, 2012 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. jaberwacky and JohnOne 2 My contributions: Performance Counters in Windows - Measure CPU, Disk, Network etc Performance | Network Interface Info, Statistics, and Traffic | CPU Multi-Processor Usage w/o Performance Counters | Disk and Device Read/Write Statistics | Atom Table Functions | Process, Thread, & DLL Functions UDFs | Process CPU Usage Trackers | PE File Overlay Extraction | A3X Script Extract | File + Process Imports/Exports Information | Windows Desktop Dimmer Shade | Spotlight + Focus GUI - Highlight and Dim for Eyestrain Relief | CrossHairs (FullScreen) | Rubber-Band Boxes using GUI's (_GUIBox) | GUI Fun! | IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) | Magnifier (Vista+) Functions UDF | _DLLStructDisplay (Debug!) | _EnumChildWindows (controls etc) | _FileFindEx | _ClipGetHTML | _ClipPutHTML + ClipPutHyperlink | _FileGetShortcutEx | _FilePropertiesDialog | I/O Port Functions | File(s) Drag & Drop | _RunWithReducedPrivileges | _ShellExecuteWithReducedPrivileges | _WinAPI_GetSystemInfo | dotNETGetVersions | Drive(s) Power Status | _WinGetDesktopHandle | _StringParseParameters | Screensaver, Sleep, Desktop Lock Disable | Full-Screen Crash Recovery Wrappers/Modifications of others' contributions: _DOSWildcardsToPCRegEx (original code: RobSaunder's) | WinGetAltTabWinList (original: Authenticity) UDF's added support/programming to: _ExplorerWinGetSelectedItems | MIDIEx UDF (original code: eynstyne) (All personal code/wrappers centrally located at Ascend4nt's AutoIT Code) Link to comment Share on other sites More sharing options...
JohnOne Posted November 28, 2012 Author Share Posted November 28, 2012 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. Link to comment Share on other sites More sharing options...
Starstar Posted April 14, 2013 Share Posted April 14, 2013 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." Link to comment Share on other sites More sharing options...
guinness Posted April 14, 2013 Share Posted April 14, 2013 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. UDF List: _AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
helsywarner Posted March 30, 2015 Share Posted March 30, 2015 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 Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now