C_82 What is Dangling pointer in C | C Language Tutorials
Summary
TLDRThis video discusses special pointers in C, focusing on the concept of dangling pointers. It explains what a dangling pointer is, the causes, and how to prevent issues related to them. Examples and code demonstrations are provided to illustrate how pointers can point to freed memory locations, leading to undefined behavior and potential bugs. The video also highlights good practices to avoid dangling pointers, such as setting pointers to null after freeing memory. Additionally, there's information about a scholarship test for GATE aspirants organized by An Academy.
Takeaways
- 📌 A dangling pointer occurs when a pointer still points to a memory location after it has been freed.
- 📌 Dangling pointers can lead to unpredictable behavior, including program crashes or garbage values.
- 📌 The `malloc` function dynamically allocates memory in C, and its memory should be freed using the `free` function to avoid memory leaks.
- 📌 Always set a pointer to `NULL` after freeing its memory to prevent it from becoming a dangling pointer.
- 📌 Checking if a pointer is `NULL` before dereferencing it is a good programming practice to avoid errors.
- 📌 A pointer becomes dangling if it points to a local variable that goes out of scope.
- 📌 Returning the address of a local variable from a function can create a dangling pointer because the local variable's memory is freed once the function returns.
- 📌 Static variables retain their memory throughout the program's execution, preventing them from becoming dangling pointers.
- 📌 The `sizeof` operator in C returns the size of a data type, which is useful for memory allocation.
- 📌 Using `static` keyword for variables ensures they have a global lifetime and do not get deallocated when going out of scope.
Q & A
What is a dangling pointer in C?
-A dangling pointer in C is a pointer that continues to point to a memory location after the memory has been freed or deallocated. Accessing this memory can lead to undefined behavior, such as program crashes or unexpected results.
What are the main causes of dangling pointers?
-The main causes of dangling pointers include deallocating memory using the free() function while still holding the pointer, using local variables' addresses outside their scope, and returning addresses of local variables from functions.
How can you prevent dangling pointers after freeing memory?
-To prevent dangling pointers after freeing memory, you can set the pointer to NULL immediately after freeing the memory. This ensures that the pointer does not point to an invalid memory location.
What happens if you dereference a dangling pointer?
-Dereferencing a dangling pointer can lead to undefined behavior, such as accessing invalid or garbage data, causing program crashes, or other unpredictable results.
How does dynamic memory allocation work with malloc()?
-Dynamic memory allocation using malloc() involves requesting a block of memory from the heap. The malloc() function returns a pointer to the beginning of the allocated memory block. The size of the memory block is specified in the malloc() call.
What is the purpose of typecasting the return value of malloc()?
-The malloc() function returns a void pointer, which is a generic pointer type. To use the allocated memory for a specific data type, you need to typecast the void pointer to the appropriate type, such as int*, float*, etc.
Why is it important to check if a pointer is NULL before dereferencing it?
-It is important to check if a pointer is NULL before dereferencing it to prevent dereferencing an invalid memory location. Dereferencing a NULL pointer typically leads to a program crash or segmentation fault.
What can happen if you use the address of a local variable outside its scope?
-Using the address of a local variable outside its scope can lead to dangling pointers because the memory for the local variable is deallocated when the function or block ends. Accessing this memory outside the scope can result in undefined behavior.
How can declaring a variable as static affect its scope and prevent dangling pointers?
-Declaring a variable as static extends its lifetime to the entire duration of the program. This means the memory for the static variable is not deallocated when the function or block ends, thus preventing dangling pointers when returning its address.
What is a good practice to follow when working with pointers to avoid bugs and crashes?
-A good practice when working with pointers is to always initialize pointers to NULL if they are not immediately assigned a valid memory address. Additionally, before dereferencing a pointer, always check if it is NULL to avoid accessing invalid memory locations.
Outlines
🖥️ Introduction to Dangling Pointers
This paragraph introduces the concept of dangling pointers in C programming. It explains what a dangling pointer is, its causes, and how to address issues arising from them. The speaker mentions an example using dynamic memory allocation and highlights the significance of understanding this topic for GATE examination aspirants. They also promote a weekly GATE scholarship test conducted by Unacademy, encouraging viewers to participate for better preparation.
🔍 Understanding Dynamic Memory Allocation
The paragraph delves deeper into dynamic memory allocation using the malloc function in C. An example is provided where a pointer is used to dynamically allocate memory for an integer. The process is explained step-by-step, including typecasting the void pointer returned by malloc to an integer pointer. The importance of correctly managing memory to avoid issues is emphasized.
📉 Freeing Memory and Dangling Pointers
This section explains what happens when dynamically allocated memory is freed. It shows that after freeing the memory, the pointer still holds the address of the freed memory, thus becoming a dangling pointer. The potential consequences of dereferencing a dangling pointer, such as unpredictable behavior and program crashes, are discussed. The analogy of having an outdated phone number is used to illustrate the concept.
🔧 Handling Dangling Pointers
This paragraph provides solutions to avoid dangling pointers. It advises setting pointers to NULL after freeing memory to prevent accidental dereferencing. The importance of checking if a pointer is NULL before dereferencing it is highlighted as a good practice to avoid program crashes and other issues. The concept of memory allocation and deallocation in the stack and heap is revisited to reinforce understanding.
🔄 Examples of Dangling Pointers
Further examples are provided to illustrate dangling pointers. One example shows how a local variable's address is returned from a function, leading to a dangling pointer once the function scope ends. Another example demonstrates how a pointer becomes dangling when it points to a local variable that goes out of scope. The importance of using static variables to extend the lifetime of variables is also discussed.
Mindmap
Keywords
💡Pointers in C
💡Dangling Pointer
💡Dynamic Memory Allocation
💡Malloc Function
💡Free Function
💡NULL Pointer
💡Undefined Behavior
💡Scope of Variables
💡Static Variables
💡GATE Examination
💡Heap Memory
Highlights
Introduction to pointers in C programming, specifically focusing on dangling pointers.
Explanation of what a dangling pointer is and the causes of dangling pointers.
Discussion on the errors that can occur in a program due to dangling pointers.
Illustration of dangling pointers through an example using dynamic memory allocation with malloc.
Demonstration of how to allocate memory dynamically and how a pointer can become a dangling pointer after freeing the allocated memory.
Explanation of how to handle dangling pointers by setting them to NULL after freeing the memory.
Introduction of a contest for GATE aspirants and its benefits for preparation.
Description of the contest format, including the number of questions and the time limit.
Mention of the live leaderboard feature in the contest to analyze rankings.
Highlight of the detailed video solutions provided after each contest to help contestants identify weak areas.
Promotion of the contest and the use of a special code (jkl10) for enrollment.
Explanation of the concept of a null pointer and its role in avoiding dereferencing dangling pointers.
Discussion on the importance of checking if a pointer is NULL before dereferencing it.
Example of a dangling pointer caused by a local variable going out of scope.
Demonstration of how a pointer can become a dangling pointer when it points to a local variable in a function that has returned.
Explanation of the difference between local and static variables in the context of dangling pointers.
Practical demonstration of a dangling pointer in a code example and the unpredictable behavior it can cause.
Conclusion and preview of the next topic to be discussed in the series, which is the wild pointer.
Transcripts
so in this phase of learning programming
in c we are discussing some special
pointers in c we have discussed void and
null pointer in this video i'll talk
about dangling pointer everything about
this pointer like what is dangling
pointer the cause of dangling pointers
and how to get rid of the situation how
to get rid of dangling pointers and if
dangling pointer comes in your program
then what type of error you can get
we will discuss with the help of program
or you can say with example i'll show
you code also on my laptop right but
before that i just want to tell you one
thing if you are preparing for gate
examination or will be preparing for
gate examination then an academy is
going to conduct a combat it's like
india's largest weekly you know
competition for gate aspirants so you
can see weekly scholarship test for gate
aspirants
here it would be on 29th of august the
time limit would be 60 minutes and 20
questions you will get and the questions
has been curated by the an academy's
best gate educators so here you will get
challenging and original gate questions
so better to take it live to compete
with the
best if you take it live then all india
live leaderboard is also there
just to you can analyze your ranking
using this letterboard because after
every questions of this
contest it will show your ranking so you
know where you are standing among all
other you know competitors
so you can assess your gate preparation
in just 60 minutes and one more thing
after every contest detailed video
solution would also be given to you by
the experts so you can you know you can
identify your weak areas and you can
improve accordingly and so that you you
get it right next time
and if you take it live you also get a
chance to win some exciting prizes you
can also see the detail over here and
it's free you don't need to pay anything
you just have to enroll for it and use
my code jkl10 for enrollment so
the enrollment link i'll put in the
description box of this video you can go
and check out so now let's see what is
this pointer before going to the
definition directly i just want to show
you one example
here i am going to use dynamic memory
allocation using mallow function right
suppose here i am taking a pointer
in
and dynamically i am going to allocate
memory here
right so suppose i am allocating memory
here
this would be syntax of
malloc function and here suppose i am
writing size of
int
if you are not getting the syntax its
okay we will discuss everything about
malloc and kellogg in later videos
for this video just you have to you know
understand this thing
i am going to ask
from the malloc function
right
this is built in function that please
allocate me
a memory dynamically dynamically means
from heap
right
how much memory size of in size of wind
means four bytes means four bytes
allocate me four bytes and mellow
return void pointer but that is why i i
am typecasting it that is why i am
writing here in star
right because pointer is what type is
what in so that is why it is returning
word pointer so i am type casting it
into in
right that that's it this is the you
know meaning of this line dynamically we
are going to allocate memory to pointer
and suppose here
uh maybe uh
in this memory now
in s3 i am storing 10.
right so here it's like something like
this here we have ptr
and dynamically suppose memory has been
allocated and sizes
size of int that is 4 byte so you can
say
4 bytes 1 2 3 4
and address is suppose 100 100 and 100
203
and it will return word pointer but i
have typecasted it so it will return
what
the obviously the base address of the
address of the first byte so 100 has
been stored in
the address over the first byte has been
stored in this point and now pointer is
pointing to this memory location
i hope you got the meaning of this line
now now in a strict ptr means value at
this is i'm accessing value
at
this point in pointer i have 100 so
value at 100
means here
i want to store so i just i'm not
representing it something like this i'm
representing it with single block size
uh sorry address is 100 so i'm storing
here 10
right now if you want to print like
printf
and
i just want to print a strict ptr
whatever the value i want to access this
value so it will give you 10
right but
if after this i have done something with
this pointer and after this i want to
free this ptr
it means
it is basically used to free
the memory
means we have
freed this memory
now
there is nothing here we have freed this
memory right we have deleted this memory
space we have freed this point
but still yeah in pointer we have
hundred
that is address of this in pointer we
have but actually we have deleted this
memory
right
this is no more reserved now
it is in what
free block of the memory
one is consumed one memories one part is
consumed memory one part is free memory
right when you you know run a program
then obviously some memory has been
allocated to you from stack also and if
you
allocate memory dynamically then from
heap also
so
here we have
two parts free memory and
consumed memory
so once we have freed this this block is
now in free memory
right so
and
before freeing this it wasn't consumed
one here so at that time it was having
some valid address
like hundred
but we have now freed this so now it is
in free block and all the memory block
here are having
invalid address right but this pointer
is still pointing to here
we haven't updated this thing
so now at this time this pointer is
acting as dangling pointer so now it is
what now
dangling pointer
here if you will dereference it like
printf percentage d and after freeing if
you will dereference it
it means
value at this address but here we don't
have anything we have deleted this
address with this memory space so it
will give you some garbage value or
maybe some undefined behavior it will
show
unpredictable behavior we cannot say
maybe program will crash or it will give
some garbage we don't know
because it is now dangling pointer
dangling is what in simple terms you
will say like
it's hanging
it is still hanging
right
but we don't have anything here
let's take one example if you have
suppose
if you have a
phone number of your friend
but
he has changed
his phone number but you still have
that old
phone number
right
so that phone number is like a pointer
you can access the your friend using
that phone number you can call your
friend using that phone number but but
now
that phone number doesn't exist
because he has changed his phone number
so now that phone number is now it's
like dangling pointer
right
you cannot access you cannot call your
friend using that phone number now if
you will call
then what would happen we don't know
maybe that has been allocated to some
other
person
right or maybe that is switched off or
we don't know anything
can be possible so here also maybe this
memory
after some time maybe that freed memory
has been allocated to do some other you
know process or some other variable or
some other kind of thing
and after that later if you will
de-reference it definitely it will show
some undefined behavior or it can cause
some bug in your program
right
it's like a risky for your you know
security purpose
right so don't leave any pointer
hanging or dangling pointer so what is
the situation how to get rid of the
situation
after freeing this
what you can do
ptr is equal to
null
better to initialize ptr with null so
now in ptr we have null that is zero
now null pointer we have already
discussed now it is pointing to it is it
is not pointing to any valid address and
we cannot dereference this null pointer
and obviously a good practice is what
further if in a program you will use
first of all we will check if
like pointer is equal to is equal to
null simply print we cannot de-reference
it hence
what you want to do with that pointer
you can do so that is a good practice
before accessing before dereferencing
any pointer in the program better to
check if pointer is null or not if null
we cannot dereference it
otherwise your program is going to be
crashed
right
so this is one reason
why dangling pointer comes this is what
you can say dear location of memory or
you can say
destruction of objects
right so it means what you can say
dangling pointer points to a
pointing to a freed memory location
right because
this has been freed
so a pointer which is pointing to a free
memory location that is known as
dangling pointer that's it
right i hope you got the definition of
dangling pointer now
one more reason why a dangling pointer
comes in your program is one reason is
this
right because you have dynamically freed
the memory and pointers still exist
right
one reason is this and how to get rid of
the situation you can point it to none
second is what in main function
i am taking a pointer
right
and
here uh maybe you write down some code
and within this code i am writing i am
taking on block like again curly braces
int a is equal to suppose 9
and in within this block i am saying ptr
is equal to address of a
and within this block i am just printing
a is equal to
and i am accessing this a using ptr so
here it will print 9
so this is the block
right where i am using this a variable
so a is what now
local variable to this block only
you can say this is the scope of this a
out of this scope if you will use this a
then it will give error because it is
local to this
right
here only you can say a would be created
a is having nine and some address also
suppose thousand
and
ptr is global
not global but within this main function
so
throughout the main
this program you can use ptr so in ptr
now we have address of a that is
thousand so ptr is now pointing to this
a
right
and here if you print strict ptr 9 would
be printed but
after this block as soon as control will
go out of this one
this would be vanished
if after this you will print printf
like directly i am printing a
you cannot access a here it will give
you error
you are accessing a local variable
it will give you error
right and after
this also if you use like a strict ptr
then also it it is acting as a dangling
pointer now because uh out of this block
now a has been vanished
this there is no a now
but this ptr is still pointing to this
memory location but there is no nothing
here
that has been you can you can say
vanished so this pointer is now it's
like hanging
so this will act as a dangling pointer
out of this
scope
right
yeah sometimes still
if you run this still maybe for a while
you can get 9
maybe you are thinking that it's wrong
but it's ok maybe for a while for some
time you can get correct output nine it
shouldn't give nine because now
nine is no more here it has been
vanished it should give any garbage but
maybe you can get nine you can run it
and you can check it but
after some other function call after
some time maybe this memory has been in
stack
instead
because when we run a program then the
some memory has been allocated
right to main function obviously that
would be copied to ram main memory so
this for a also some memory has been
allocated for ptr also some memory has
been allocated for also memory has been
allocated this is what within this scope
only scope is this one out of this this
would be vanished
right
so maybe for a while you can get nine
same output
but
after some time after other function
call after in your program
this memory maybe will be allocated by
the operating system to some other
variable to some other function
then if you will dereference it using
this pointer it will give some garbage
value
right
but yeah it will act out of the scope as
a dangling pointer
right
third reason may be like
one one
before this main function before this
main function i am taking one function
like
f and i am taking here
a is equal to 10
and here i am returning return address
of a
this function is returning address of
this variable
right and within main function within
main function what i am writing
so it is returning address
so
to catch address to store address of any
variable we should have some pointer
variable so here i am having pointer
variable
and whatever this function return f
return
that would be stored in this pointer
right it is returning address so that is
why it is int star
string
right
so it will read an address and this
pointer is going to
store that address and within main
function i'm writing like i'm
dereferencing this as strict ptr like
whatever the value at that address it
should be printed like it should be
printed 10 because it will get an
address of a
so in a we have 10 so it should print 10
but
here this ptr is acting as a dangling
pointer why so same
this a is within this function so scope
of this a is within this function only
right
now it will return address of a
but
after returning as soon as control will
go out of this function
this a would be vanished it would be
deleted
so now
here this pointer is obviously it has
returned the address here
right
so in ptr we have address of a but as
soon as control will go out of this
function in the main function here
here because i am calling function here
one the control will go out of this one
this would be vanished
so now
what this pointer is still hanging
because whatever the address it is
containing that is no more now that
memory is now freed
it has been vanished
right so now also it is acting as a
dangling pointer
and if you will you know like
de-reference it maybe it will give some
garbage value to you and see here
if because this scope of this is within
this function only but if you declare it
static
static variables are having scope but
global globally means throughout the
program
so if you declare it
static
then it is not going to vanish it will
return address of this a and if in main
function if you will dereference it it
will give you 10.
now it's fine now it is not acting as
dangling pointer right because we have
used static here this also will discuss
in detail but for
this video you have to take you know how
to understand this thing
static variables these are having
you know scope you can say globally or
throughout the program
right
so now let me show you uh you know
practically what is dangling pointer so
now let me create a file
header file we use and uh
we also use one more header file that is
stdlib
because here we use like for that
malloc and malloc function dynamic
memory allocation and that is built-in
function that has been i know
uh defined in this header file stdlib
right
so first of all i am taking like uh that
same
one pointer
and dynamically
what
we are allocating memory
using
malloc so
size of
and we have allocated like the memory so
that
in that memory i am storing
10
and i am printing
percentage d
i'm accessing that thing using
that memory using pointer only
right
so i guess it should print what 10
if the syntax is correct so let's see
what happens
here
say it is giving output 10
right
so now
what i'm doing
now free the memory
whatever the memory pointer is pointing
free that
this is the syntax of this free function
free and just you have to pass the
pointer which is pointing to that memory
location so that memory has been free
like vanished
but pointer is still pointing to that so
now pointer is acting as a dangling
pointer so now if you will access this
like printf
again here i am using
a strict ptr
what it should give
you don't know maybe it will give some
garbage value
see
10 first time and after that it is
giving some garbage value
right and suppose again
run this at this time again
some another value garbage value right
so this is what dangling pointer so how
you can get rid of the situation
after freeing directly you know simply
do
ptr is equal to null
and you cannot dereference null pointer
so please don't dereference null pointer
now before dereferencing in a program
good practice is what use sorry check
if this is null pointer is null you
cannot dereference it else you can do
whatever you want to do with that
pointer so one situation is this
next can be
next can be like i am just going to
comment this out
right
and next we are using that
function
right so
before using this main function what i
am defining a function f
and here i am taking a variable int is
equal to 9 and
return what address of a
that's it and in main function what
we will take a pointer because
to store address obviously we need a
pointer variable
so whatever this function will return
this pointer is going to take right and
after that
we are printing
i'm writing this line like printf
percentage d
and strict ptr so i'm accessing this ptr
now
right
so let's see what happens let me run
this
see
it is not returning anything like no
output you are getting and the function
returns address of a local variable
address of a is local variable right so
here this ptr is acting as a dangling
pointer you are not getting any output
right
maybe sometimes it will give any garbage
value it
we cannot say it will show some
unpredictable behavior
right
and
next is what
if i am taking a pointer here
right suppose pointer is equal to so
better to initialize
a pointer at starting when you take a
pointer better to initialize it with the
null
so if you are not initializing here with
any valid address so better to
initialize it with
null so next case is uh i'm not taking
this function now i'm deleting it
so pti is equal to null and here i am
taking
like
within this block i am taking a variable
a is equal to five 5
and
here ptr is equal to address of
a
and i am printing printf
a is equal to whatever the value is
having i'm accessing this using
ptr so a strict media
right
suppose this line i'm going to comment
it out right so this is what we have see
this is what we have
right so what output you will get
obviously you will get 5
right
see a is equal to 5
but ah
out of this
block this is the scope of the say if
out of this using this printf statement
out of this block i am accessing
strict ptr
now here it is acting as dangling
pointer
so it will show some unpredictable
behavior maybe a program will crash or
it will give some bug or
it can it can create some bug or it will
give some garbage value we cannot say
but sometimes it will give the same
value that is 5 it is also possible see
let me run this and see what happens
okay what
just a minute
now let me run this
see a is equal to 5
for this a is equal to 5 and this printf
is also giving you 5
but although the scope of this a is
within this only it has been vanished
but still it is giving you 5.
it is also possible for a while it this
will give you correct output
but after some time when you write some
other in your program maybe that you
know freed memory location would be
allocated to some other function or some
other variable
so after that this this pointer this
line this pointer will show
it will not give you correct output it
will show some unpredictable behavior
right so this is also fine maybe you are
thinking it is giving 5 so it is i know
it is not correct but no yeah it can
give you some you know correct result
for uh for some time for a while you can
say
so that's it for this video now so i
hope you got what is dangling pointer
and see when we are left with one more
pointer that is wild point tennessee so
now that thing we'll discuss in next
video so i'll see in the next video till
then bye take care
Voir Plus de Vidéos Connexes
5.0 / 5 (0 votes)