Share to: share facebook share twitter share wa share telegram print page

Dangling pointer

Dangling pointer

Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type. These are special cases of memory safety violations. More generally, dangling references and wild references are references that do not resolve to a valid destination.

Dangling pointers arise during object destruction, when an object that has an incoming reference is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory. The system may reallocate the previously freed memory, and if the program then dereferences the (now) dangling pointer, unpredictable behavior may result, as the memory may now contain completely different data. If the program writes to memory referenced by a dangling pointer, a silent corruption of unrelated data may result, leading to subtle bugs that can be extremely difficult to find. If the memory has been reallocated to another process, then attempting to dereference the dangling pointer can cause segmentation faults (UNIX, Linux) or general protection faults (Windows). If the program has sufficient privileges to allow it to overwrite the bookkeeping data used by the kernel's memory allocator, the corruption can cause system instabilities. In object-oriented languages with garbage collection, dangling references are prevented by only destroying objects that are unreachable, meaning they do not have any incoming pointers; this is ensured either by tracing or reference counting. However, a finalizer may create new references to an object, requiring object resurrection to prevent a dangling reference.

Wild pointers, also called uninitialized pointers, arise when a pointer is used prior to initialization to some known state, which is possible in some programming languages. They show the same erratic behavior as dangling pointers, though they are less likely to stay undetected because many compilers will raise a warning at compile time if declared variables are accessed before being initialized.[1]

Cause of dangling pointers

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 that location 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 may 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

Antoni Kreczmar [pl] (1945–1996) has created a complete object management system which is free of dangling reference phenomenon.[2] A similar approach was proposed by Fisher and LeBlanc[3] under the name Locks-and-keys.

Cause of wild pointers

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

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.[4] For example, CVE-2014-1776 is a use-after-free vulnerability in Microsoft Internet Explorer 6 through 11[5] being used by zero-day attacks by an advanced persistent threat.[6]

Avoiding dangling pointer errors

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()' */
static void safefree(void **pp)
{
    /* in debug mode, abort if pp is NULL */
    assert(pp);
    /* free(NULL) works properly, so no check is required besides the assert in debug mode */
    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 as p is reset to NULL */
    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 (a common one being #define XFREE(ptr) safefree((void **)&(ptr))), 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.[3]

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 has 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

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[7]). 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,[8] AddressSanitizer, or tools based on LLVM[9] 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.

See also

References

  1. ^ "Warning Options - Using the GNU Compiler Collection (GCC)".
  2. ^ Gianna Cioni, Antoni Kreczmar, Programmed deallocation without dangling reference, Information Processing Letters, v. 18, 1984, pp. 179–185
  3. ^ a b C. N. Fisher, R. J. Leblanc, The implementation of run-time diagnostics in Pascal , IEEE Transactions on Software Engineering, 6(4):313–319, 1980.
  4. ^ Dalci, Eric; anonymous author; CWE Content Team (May 11, 2012). "CWE-416: Use After Free". Common Weakness Enumeration. Mitre Corporation. Retrieved April 28, 2014. {{cite web}}: |author2= has generic name (help)
  5. ^ "CVE-2014-1776". Common Vulnerabilities and Exposures (CVE). 2014-01-29. Archived from the original on 2017-04-30. Retrieved 2017-05-16.
  6. ^ 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.
  7. ^ Visual C++ 6.0 memory-fill patterns
  8. ^ Mudflap Pointer Debugging
  9. ^ Dhurjati, D. and Adve, V. Efficiently Detecting All Dangling Pointer Uses in Production Servers

Read other articles:

Achille Lauro (1965) Astillero Damen Schelde Naval ShipbuildingTipo crucero y transatlánticoOperador MSC Cruceros y Royal Rotterdam LloydAsignado 1947Baja 2 de diciembre de 1994Eslora 196 metrosManga 25,1 metrosCalado 8,9 metrosVelocidad 22 nudos[editar datos en Wikidata] El Achille Lauro en 1989 El Achille Lauro fue un crucero con base en Nápoles, (Italia). Fue construido entre 1939 y 1947 con el nombre Willem Ruys, como barco de línea de pasajeros para la empresa Rotterdamsche ...

Стефан Боца Єпископ Горнокарловацький (з лютого 1941 - тимчас. кер. Пакрацької єпархії) з 22 червня 1938 Єпископ Сремський, голова Єпархіального управління Белградсько-Карловацької архієпископії 30 вересня 1934 — початок 1937   Альма-матер: Карловацька духовна семінарі...

Sebastian Witowski Sebastian Witowski w barwach Cracovii (2012) Data i miejsce urodzenia 13 września 1976 Polska Obywatelstwo Polska Wzrost 178 cm Pozycja napastnik / obrońca Sebastian Witowski (ur. 13 września 1976) – polski hokeista. Kariera KTH Krynica (1997-2002) Cracovia (2002-2015) Wychowanek KTH Krynica. Wieloletni zawodnik Cracovii. Po sezonie Polska Hokej Liga (2014/2015) zakończył karierę zawodniczą i został kierownikiem drużyny Cracovii[1][2]. W trakcie kariery zokr...

العلاقات البوروندية الفيجية بوروندي فيجي   بوروندي   فيجي تعديل مصدري - تعديل   العلاقات البوروندية الفيجية هي العلاقات الثنائية التي تجمع بين بوروندي وفيجي.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه المقارنة بوروند

Longuinhos dos SantosSantos pada 2018Menteri Perguruan Tinggi, Sains dan BudayaPetahanaMulai menjabat 22 Juni 2018 (2018-06-22)Perdana MenteriTaur Matan RuakPendahuluFernando Hanjam Informasi pribadiPartai politikPartai Pembebasan Rakyat (PLP)Sunting kotak info • L • B Longuinhos dos Santos adalah seorang politikus Timor Leste, dan anggota Partai Pembebasan Rakyat (PLP). Ia adalah Menteri Perguruan Tinggi, Sains dan Budaya petahana, yang menjabat sejak Juni 2018 di bawa...

This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Bára Nesvadbová –&#...

Vidhan Sabha constituencyNalaConstituency No. 8 for the Jharkhand Legislative AssemblyConstituency detailsCountryIndiaRegionEast IndiaStateJharkhandDistrictJamtaraLS constituencyDumkaEstablished2000Total electors2,23,179Member of Legislative Assembly5th Jharkhand Legislative AssemblyIncumbent Rabindra Nath Mahato Party  JMMElected year2019 Nala Assembly constituency is an assembly constituency in the Indian state of Jharkhand.[1] Overview Nala Assembly constituency covers: N...

Swedish professional golfer Louise StahleStahle in 2019Personal informationBorn (1985-03-19) 19 March 1985 (age 38)Lund, SwedenHeight1.75 m (5 ft 9 in)Sporting nationality SwedenResidenceScottsdale, Arizona, U.S.CareerCollegeArizona State UniversityTurned professional2005Current tour(s)LPGA Tour (joined 2006) Ladies European Tour (joined 2007)Professional wins2Best results in LPGA major championshipsChevron ChampionshipDNPWomen's PGA C'shipT67: 2010U.S. Women's OpenT4...

English footballer Michael Ngoo Personal informationFull name Michael Ayodeji D. NgooDate of birth (1992-10-23) 23 October 1992 (age 31)Place of birth Walthamstow, London, England[1]Height 6 ft 6 in (1.98 m)[2][3][4]Position(s) StrikerYouth career2008–2009 Southend United2009–2013 LiverpoolSenior career*Years Team Apps (Gls)2013–2014 Liverpool 0 (0)2013 → Heart of Midlothian (loan) 15 (4)2013 → Yeovil Town (loan) 6 (0)2014 → Wals...

1975 concert tour of North America by Led Zeppelin North America 1975Tour by Led ZeppelinPoster for Led Zeppelin's concert at Baton Rouge, used to help promote its 1975 North American tourLocationUnited StatesCanadaAssociated albumPhysical GraffitiStart date18 January 1975End date27 March 1975Legs3No. of shows37 (and two European warm-up shows) (38 scheduled)Led Zeppelin concert chronology North America 1973 North America 1975 Earls Court 1975 Led Zeppelin's 1975 North American Tour was the t...

Japanese voice actor This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: Nanami Yamashita – news · newspapers · books · scholar · JSTOR (September 2023) (Learn how and when to remove this template m...

Type of mating fastener Barrel bolt redirects here. For the type of latch called a barrel bolt, see Latch (hardware). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Sex bolt – news · newspapers · books · scholar · JSTOR (April 2018) (Learn how and when to remove this template message) Sleeve nuts, one with ...

Part of a series onHorror films History Lists By decade 1896–1959 1890s 1900s 1910s 1920s 1930s 1940s 1950s 1960s 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970s 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980s 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990s 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000s 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010s 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020s 2020 2021 2022 2023 2024 By region Asia India...

Eighth Xhosa WarPart of the Xhosa WarsResistance fighters defend a stronghold in the forested Water Kloof during the Eighth Xhosa War in 1851. Xhosa, Kat River Khoi-khoi and some army deserters are depictedDate1850–1853[4]LocationCape Colony frontierResult British victory[4]Belligerents British Empire Cape Colony Xhosa tribes Ngqika people[1] Khoikhoi forces[2] Cape Mounted Riflemen renegades[3]Commanders and leaders Harry Smith[5] (until 1852...

Armenian politician Rustam GasparyanArmenian: Ռուստամ ԳասպարյանMember of the Parliament of ArmeniaIn office19 June 2007 – 31 May 2012 Personal detailsBorn(1961-04-11)April 11, 1961Janfida, Armenian SSR, USSRDiedOctober 17, 2020(2020-10-17) (aged 59)Hadrut Province, Republic of Artsakh (de facto)Citizenship ArmeniaChildren2EducationArmavir Ararat UniversityOccupationPolitician Military commanderMilitary serviceAllegiance Armenia  ArtsakhBranch/ser...

Football simulation game 2020 video gameFIFA 21Current Gen Standard cover art featuring Paris Saint-Germain player Kylian MbappéDeveloper(s)EA VancouverEA RomaniaPublisher(s)EA SportsSeriesFIFAEngineFrostbite 3Platform(s)Microsoft WindowsNintendo SwitchPlayStation 4Xbox OneStadiaPlayStation 5Xbox Series X/SReleaseMicrosoft Windows, Nintendo Switch, PS4, Xbox One9 October 2020PS5, Xbox Series X/S3 December 2020Stadia17 March 2021Genre(s)SportsMode(s)Single-player, multiplayer FIFA 21 is an as...

This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) The neutrality of this article is disputed. Relevant discussion may be found on the talk page. Please do not remove this message until conditions to do so are met. (November 2019) (Learn how and when to remove this template message) This article contains content that is written like an advertisement. Please help improve it by removing promot...

Unincorporated community in Illinois, United StatesWoodburn, IllinoisUnincorporated communityWoodburnShow map of IllinoisWoodburnShow map of the United StatesCoordinates: 39°02′51″N 90°00′43″W / 39.04750°N 90.01194°W / 39.04750; -90.01194CountryUnited StatesStateIllinoisCountyMacoupinEstablished1834Elevation640 ft (195 m)Population (1911) • Total175Time zoneUTC-6 (Central (CST)) • Summer (DST)UTC-5 (CDT)ZIP code62014Ar...

Petri dish with agar used to culture microbes Agar plateUsesMicrobiological cultureArtRelated itemsPetri dishGrowth medium Contamination on an agar plate An agar plate is a Petri dish that contains a growth medium solidified with agar, used to culture microorganisms. Sometimes selective compounds are added to influence growth, such as antibiotics.[1]96 pinner used to perform spot assays with yeast, fungal or bacterial cells Individual microorganisms placed on the plate will grow into ...

United States historic placeMcCarty Memorial Christian ChurchU.S. National Register of Historic Places Show map of the Los Angeles metropolitan areaShow map of CaliforniaShow map of the United StatesLocationLos Angeles, CaliforniaCoordinates34°2′6″N 118°19′44″W / 34.03500°N 118.32889°W / 34.03500; -118.32889Built1932ArchitectBarber, Thomas P.; Kingsbury, PaulArchitectural styleLate Gothic RevivalNRHP reference No.01001456[1]Added to N...

Kembali kehalaman sebelumnya