Contents 1 Cause of dangling pointers 2 Manual deallocation without dangling reference 3 Cause of wild pointers 4 Security holes involving dangling pointers 5 Avoiding dangling pointer errors 6 Dangling pointer detection 7 Other uses 8 See also 9 References

Cause of dangling pointers[edit] In many languages (e.g., the C programming language) deleting an object from memory explicitly or by destroying the stack frame on return does not alter associated pointers. The pointer still points to the same location in memory even though the reference has since been deleted and may now be used for other purposes. A straightforward example is shown below: { char *dp = NULL; /* ... */ { char c; dp = &c; } /* c falls out of scope */ /* dp is now a dangling pointer */ } If the operating system is able to detect run-time references to null pointers, a solution to the above is to assign 0 (null) to dp immediately before the inner block is exited. Another solution would be to somehow guarantee dp is not used again without further initialization. Another frequent source of dangling pointers is a jumbled combination of malloc() and free() library calls: a pointer becomes dangling when the block of memory it points to is freed. As with the previous example one way to avoid this is to make sure to reset the pointer to null after freeing its reference—as demonstrated below. #include <stdlib.h> void func() { char *dp = malloc(A_CONST); /* ... */ free(dp); /* dp now becomes a dangling pointer */ dp = NULL; /* dp is no longer dangling */ /* ... */ } An all too common misstep is returning addresses of a stack-allocated local variable: once a called function returns, the space for these variables gets deallocated and technically they have "garbage values". int *func(void) { int num = 1234; /* ... */ return &num; } Attempts to read from the pointer may still return the correct value (1234) for a while after calling func, but any functions called thereafter will overwrite the stack storage allocated for num with other values and the pointer would no longer work correctly. If a pointer to num must be returned, num must have scope beyond the function—it might be declared as static.

Manual deallocation without dangling reference[edit] This section may rely excessively on sources too closely associated with the subject, potentially preventing the article from being verifiable and neutral. Please help improve it by replacing them with more appropriate citations to reliable, independent, third-party sources. (June 2014) (Learn how and when to remove this template message) This article needs attention from an expert on the subject. The specific problem is: incomprehensible snippet from a paper. When placing this tag, consider associating this request with a WikiProject. (June 2014) Antoni Kreczmar (pl) (1945-1996) has created a complete object management system which is free of dangling reference phenomenon, see[2] Scheme of axioms of the operation kill Let x1, ... ,xn be variables, n > 0, 1≤i≤n. Each formula of the following scheme is a theorem of the virtual machine constructed by Kreczmar. ( x 1 = ⋯ = x n ≠ n o n e ) ⏟ p r e c o n d i t i o n ⇒ [ k i l l ( x i ) ] ⏟ s t a t e m e n t ( x 1 = ⋯ = x n = n o n e ) ⏟ p o s t c o n d i t i o n {\displaystyle \underbrace {(x_{1}=\dots =x_{n}\neq none)} _{\mathrm {precondition} }\Rightarrow \underbrace {[kill(x_{i})]} _{\mathrm {} statement}\underbrace {(x_{1}=\dots =x_{n}=none)} _{\mathrm {postcondition} }} read as: if an object o is the value of n variables, then after execution of instruction kill(xi) the common value of these variables is none (it means that from this moment the object o is unreachable and consequently the portion of the memory occupied by it can be by the same operation kill recycled without any harm). Consequently: there is no need to repeat the operation kill(x1), kill(x2), ...[3] there is no phenomenon of dangling reference, any attempt to access the deleted object, will be detected and signalized as an exception „reference to none”. Note: the cost of kill is constant O ( 1 ) {\displaystyle O(1)} . A similar approach was proposed by Fisher and LeBlanc [4] under the name Locks-and-keys.

Cause of wild pointers[edit] Wild pointers are created by omitting necessary initialization prior to first use. Thus, strictly speaking, every pointer in programming languages which do not enforce initialization begins as a wild pointer. This most often occurs due to jumping over the initialization, not by omitting it. Most compilers are able to warn about this. int f(int i) { char *dp; /* dp is a wild pointer */ static char *scp; /* scp is not a wild pointer: * static variables are initialized to 0 * at start and retain their values from * the last call afterwards. * Using this feature may be considered bad * style if not commented */ }

Security holes involving dangling pointers[edit] Like buffer-overflow bugs, dangling/wild pointer bugs frequently become security holes. For example, if the pointer is used to make a virtual function call, a different address (possibly pointing at exploit code) may be called due to the vtable pointer being overwritten. Alternatively, if the pointer is used for writing to memory, some other data structure may be corrupted. Even if the memory is only read once the pointer becomes dangling, it can lead to information leaks (if interesting data is put in the next structure allocated there) or to privilege escalation (if the now-invalid memory is used in security checks). When a dangling pointer is used after it has been freed without allocating a new chunk of memory to it, this becomes known as a "use after free" vulnerability.[5] For example, CVE-2014-1776 is a use-after-free vulnerability in Microsoft Internet Explorer 6 through 11[6] being used by zero-day attacks by an advanced persistent threat.[7]

Avoiding dangling pointer errors[edit] In C, the simplest technique is to implement an alternative version of the free() (or alike) function which guarantees the reset of the pointer. However, this technique will not clear other pointer variables which may contain a copy of the pointer. #include <assert.h> #include <stdlib.h> /* Alternative version for 'free()' */ void safefree(void **pp) { /* in debug mode, abort if pp is NULL */ assert(pp); if (pp != NULL) { /* safety check */ free(*pp); /* deallocate chunk, note that free(NULL) is valid */ *pp = NULL; /* reset original pointer */ } } int f(int i) { char *p = NULL, *p2; p = malloc(1000); /* get a chunk */ p2 = p; /* copy the pointer */ /* use the chunk here */ safefree((void **)&p); /* safety freeing; does not affect p2 variable */ safefree((void **)&p); /* this second call won't fail */ char c = *p2; /* p2 is still a dangling pointer, so this is undefined behavior. */ return i + c; } The alternative version can be used even to guarantee the validity of an empty pointer before calling malloc(): safefree(&p); /* i'm not sure if chunk has been released */ p = malloc(1000); /* allocate now */ These uses can be masked through #define directives to construct useful macros, creating something like a metalanguage or can be embedded into a tool library apart. In every case, programmers using this technique should use the safe versions in every instance where free() would be used; failing in doing so leads again to the problem. Also, this solution is limited to the scope of a single program or project, and should be properly documented. Among more structured solutions, a popular technique to avoid dangling pointers in C++ is to use smart pointers. A smart pointer typically uses reference counting to reclaim objects. Some other techniques include the tombstones method and the locks-and-keys method (see paper by Fisher & LeBlanc). Another approach is to use the Boehm garbage collector, a conservative garbage collector that replaces standard memory allocation functions in C and C++ with a garbage collector. This approach completely eliminates dangling pointer errors by disabling frees, and reclaiming objects by garbage collection. In languages like Java, dangling pointers cannot occur because there is no mechanism to explicitly deallocate memory. Rather, the garbage collector may deallocate memory, but only when the object is no longer reachable from any references. In the language Rust, the type system have been extended to include also the variables lifetimes and resource acquisition is initialization. Unless one disables the features of the language, dangling pointers will be caught at compile time and reported as programming errors.

Dangling pointer detection[edit] To expose dangling pointer errors, one common programming technique is to set pointers to the null pointer or to an invalid address once the storage they point to has been released. When the null pointer is dereferenced (in most languages) the program will immediately terminate—there is no potential for data corruption or unpredictable behavior. This makes the underlying programming mistake easier to find and resolve. This technique does not help when there are multiple copies of the pointer. Some debuggers will automatically overwrite and destroy data that has been freed, usually with a specific pattern, such as 0xDEADBEEF (Microsoft's Visual C/C++ debugger, for example, uses 0xCC, 0xCD or 0xDD depending on what has been freed[8]). This usually prevents the data from being reused by making it useless and also very prominent (the pattern serves to show the programmer that the memory has already been freed). Tools such as Polyspace, TotalView, Valgrind, Mudflap,[9] AddressSanitizer, or tools based on LLVM[10] can also be used to detect uses of dangling pointers. Other tools (SoftBound, Insure++, and CheckPointer) instrument the source code to collect and track legitimate values for pointers ("metadata") and check each pointer access against the metadata for validity. Another strategy, when suspecting a small set of classes, is to temporarily make all their member functions virtual: after the class instance has been destructed/freed, its pointer to the Virtual Method Table is set to NULL, and any call to a member function will crash the program and it will show the guilty code in the debugger.

Other uses[edit] The term dangling pointer may also be used in contexts other than programming, especially by technical people. For example, a phone number for a person who has since changed phones is a real-world example of a dangling pointer.[11] Another example is an entry in an online encyclopedia that refers to another entry whose title has been changed, changing any previously existing references to that entry into dangling pointers.

See also[edit] Software Testing portal Common Vulnerabilities and Exposures Memory debugger Wild branch

References[edit] ^ ^ Gianna Cioni, Antoni Kreczmar, Programmed deallocation without dangling reference, Information Processing Letters, v. 18, 1984, pp.179-185 ^ In C++ putting the instructions delete(x1,);...delete(xn); is the only way to avoid the error of dangling pointer. ^ C.N. Fisher, R.J. Leblanc, The implementation of run-time diagnostics in Pascal , IEEE Trans. Softw. Eng., 6(4):313-319, 1980 ^ Dalci, Eric; anonymous author; CWE Content Team (May 11, 2012). "CWE-416: Use After Free". Common Weakness Enumeration. Mitre Corporation. Retrieved April 28, 2014.  ^ "CVE-2014-1776". Common Vulnerabilities and Exposures (CVE). 2014-01-29. Retrieved 2017-05-16.  ^ Chen, Xiaobo; Caselden, Dan; Scott, Mike (April 26, 2014). "New Zero-Day Exploit targeting Internet Explorer Versions 9 through 11 Identified in Targeted Attacks". FireEye Blog. FireEye. Retrieved April 28, 2014.  ^ Visual C++ 6.0 memory-fill patterns ^ Mudflap Pointer Debugging ^ Dhurjati, D. and Adve, V. Efficiently Detecting All Dangling Pointer Uses in Production Servers ^ "The Jargon File". version 4.4.7. Retrieved 2014-01-07.  v t e Memory management Memory management as a function of an operating system Manual memory management Static memory allocation C dynamic memory allocation new and delete (C++) Virtual memory Demand paging Page table Paging Virtual memory compression Hardware Memory management unit Translation lookaside buffer Garbage collection Boehm garbage collector Concurrent mark sweep collector Finalizer Garbage Garbage-first collector Mark-compact algorithm Reference counting Tracing garbage collection Strong reference Weak reference Memory segmentation Protected mode Real mode Virtual 8086 mode x86 memory segmentation Memory safety Buffer overflow Buffer over-read Dangling pointer Stack overflow Issues Fragmentation Memory leak Unreachable memory Other Automatic variable International Symposium on Memory Management Region-based memory management Retrieved from "" Categories: Software bugsComputer security exploitsHidden categories: Articles lacking reliable references from June 2014All articles lacking reliable referencesArticles needing unspecified expert attentionArticles needing expert attention from June 2014All articles needing expert attentionInterlanguage link template link number

Navigation menu Personal tools Not logged inTalkContributionsCreate accountLog in Namespaces ArticleTalk Variants Views ReadEditView history More Search Navigation Main pageContentsFeatured contentCurrent eventsRandom articleDonate to WikipediaWikipedia store Interaction HelpAbout WikipediaCommunity portalRecent changesContact page Tools What links hereRelated changesUpload fileSpecial pagesPermanent linkPage informationWikidata itemCite this page Print/export Create a bookDownload as PDFPrintable version Languages DeutschEspañolفارسیFrançais한국어ItalianoМонголPortuguêsРусскийУкраїнська中文 Edit links This page was last edited on 30 January 2018, at 21:18. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Privacy policy About Wikipedia Disclaimers Contact Wikipedia Developers Cookie statement Mobile view (window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgPageParseReport":{"limitreport":{"cputime":"0.168","walltime":"0.249","ppvisitednodes":{"value":816,"limit":1000000},"ppgeneratednodes":{"value":0,"limit":1500000},"postexpandincludesize":{"value":30105,"limit":2097152},"templateargumentsize":{"value":555,"limit":2097152},"expansiondepth":{"value":12,"limit":40},"expensivefunctioncount":{"value":3,"limit":500},"entityaccesscount":{"value":0,"limit":400},"timingprofile":["100.00% 176.120 1 -total"," 37.92% 66.789 1 Template:Reflist"," 31.30% 55.123 1 Template:Third-party"," 29.21% 51.444 4 Template:Cite_web"," 17.39% 30.625 2 Template:Ambox"," 7.22% 12.714 1 Template:Ill"," 6.88% 12.116 1 Template:Memory_management_navbox"," 6.85% 12.058 1 Template:Expert_needed"," 5.72% 10.067 1 Template:Portal"," 5.51% 9.713 1 Template:DMCA"]},"scribunto":{"limitreport-timeusage":{"value":"0.068","limit":"10.000"},"limitreport-memusage":{"value":2732304,"limit":52428800}},"cachereport":{"origin":"mw1267","timestamp":"20180217151453","ttl":1900800,"transientcontent":false}}});});(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgBackendResponseTime":89,"wgHostname":"mw1270"});});

Dangling_pointer - Photos and All Basic Informations

Dangling_pointer More Links

EnlargeComputer ProgrammingData PointerMemory SafetyReference (computer Science)Link RotObject DestructionDereference OperatorUndefined BehaviorSoftware BugSegmentation FaultGeneral Protection FaultObject-oriented LanguageGarbage Collection (computer Science)Reference CountingFinalizerObject ResurrectionC (programming Language)Null PointerStatic VariableWikipedia:VerifiabilityWikipedia:Neutral Point Of ViewWikipedia:Citing SourcesWikipedia:Identifying And Using Independent SourcesHelp:Maintenance Template RemovalTemplate:Expert NeededWikipedia:WikiProjectDangling ReferenceLocks-and-keysBuffer OverflowVirtual FunctionVtablePrivilege EscalationZero-day AttackAdvanced Persistent ThreatSmart PointerReference CountingTombstone (programming)Locks-and-keysBoehm Garbage CollectorGarbage Collection (computer Science)C++Rust (programming Language)Type SystemResource Acquisition Is InitializationNull Pointer0xDEADBEEFPolyspaceTotalViewValgrindAddressSanitizerLLVMInsure++Virtual MethodVirtual Method TableOnline EncyclopediaPortal:Software TestingCommon Vulnerabilities And ExposuresMemory DebuggerWild BranchMitre CorporationFireEyeTemplate:Memory ManagementTemplate Talk:Memory ManagementMemory ManagementMemory Management (operating Systems)Manual Memory ManagementStatic VariableC Dynamic Memory AllocationNew And Delete (C++)Virtual MemoryDemand PagingPage TablePagingVirtual Memory CompressionMemory Management UnitTranslation Lookaside BufferGarbage Collection (computer Science)Boehm Garbage CollectorConcurrent Mark Sweep CollectorFinalizerGarbage (computer Science)Garbage-first CollectorMark-compact AlgorithmReference CountingTracing Garbage CollectionWeak ReferenceWeak ReferenceMemory SegmentationProtected ModeReal ModeVirtual 8086 ModeX86 Memory SegmentationMemory SafetyBuffer OverflowBuffer Over-readStack OverflowFragmentation (computing)Memory LeakUnreachable MemoryAutomatic VariableInternational Symposium On Memory ManagementRegion-based Memory ManagementHelp:CategoryCategory:Software BugsCategory:Computer Security ExploitsCategory:Articles Lacking Reliable References From June 2014Category:All Articles Lacking Reliable ReferencesCategory:Articles Needing Unspecified Expert AttentionCategory:Articles Needing Expert Attention From June 2014Category:All Articles Needing Expert AttentionCategory:Interlanguage Link Template Link NumberDiscussion About Edits From This IP Address [n]A List Of Edits Made From This IP Address [y]View The Content Page [c]Discussion About The Content Page [t]Edit This Page [e]Visit The Main Page [z]Guides To Browsing WikipediaFeatured Content – The Best Of WikipediaFind Background Information On Current EventsLoad A Random Article [x]Guidance On How To Use And Edit WikipediaFind Out About WikipediaAbout The Project, What You Can Do, Where To Find ThingsA List Of Recent Changes In The Wiki [r]List Of All English Wikipedia Pages Containing Links To This Page [j]Recent Changes In Pages Linked From This Page [k]Upload Files [u]A List Of All Special Pages [q]Wikipedia:AboutWikipedia:General Disclaimer

view link view link view link view link view link