Im trying to understand more about pointers. Basically what im trying to do is to have a pointer passed into a function that accepts a pointer. Inside, i created a local pointer that points to the pointer passed into the function. I modified the value of the local pointer.
When this happens, it seems that it also modifies the value of the original y variable outside of the function. So if i'm assumingly correctly, that means unlike usual variables, local pointers directly links to pointers outside of the function.
Now based on the example, how should i free my pointers? I think i need to free my *ptr_y, but what about *x_ptr ? I can't free x_ptr since it might also free ptr_y accidentally? -
#include <stdlib.h>
-
#include <stdio.h>
-
-
-
void myfunction(int *x)
-
{
-
int *x_ptr = NULL;
-
-
x_ptr = x;
-
-
*x_ptr = 1111;
-
-
printf("%myfunction local pointer is %d\r\n", *x_ptr);
-
-
-
}
-
-
int main(int argc, char* argv[])
-
{
-
-
int y = 5;
-
int *ptr_y;
-
-
ptr_y = &y;
-
-
printf("y starts with %d\r\n", y);
-
-
myfunction(ptr_y);
-
-
y = 6;
-
-
myfunction(ptr_y);
-
-
printf("at the end, y is %d\r\n", y);
-
return 0;
-
}
-
-
Like I said, Mem2 and Mem both point to the same block of memory. If you call delete on any of those, and ANY time, the memory will be freed. Doesn't matter if you make another pointer point to the same memory within a function, it's just so you have reference to an object inside the function rather than passing all of the memory to the function, you just pass the address of the allocated memory.
The following program is perfectly fine, causing no memory leaks: -
-
int main()
-
{
-
// An integer (4 bytes) is allocated in heap memory.
-
int *Mem = new int;
-
-
// Call a function, passing the POINTER, not the
-
// actual int in memory, just a pointer to it.
-
FunctionCall(Mem);
-
-
// Good memory management says that you delete the
-
// allocated memory in the same scope that it was
-
// created.
-
delete Mem;
-
-
return 0;
-
}
-
-
// This function accepts a POINTER to some memory.
-
void FunctionCall(int *Mem)
-
{
-
// This is just a pointer, a MEMORY ADDRESS.
-
// NOTHING has been allocated on the heap when
-
// declaring this variable.
-
int *Mem2;
-
-
// Make the Mem2 POINTER POINT to the same block
-
// of memory that Mem points to. Once again,
-
// NOTHING new has been allocated in heap memory.
-
Mem2 = Mem;
-
-
// Change something in the memory location by
-
// de-referencing it with a '*'.
-
*Mem2 = 1234;
-
-
// At the end of this function, Mem and Mem2 will
-
// both return 1234 when de-referenced as they both
-
// point to the SAME block of memory.
-
-
// NO deletion is done here as the memory was
-
// allocated outside the function (this is what
-
// the function assumes).
-
}
-
I couldn't have explained it in more depth right now, i hope this helps you.
7 12514
on entry to myfunction() pointer x contains the address of y in main()
so when you copy x to x_ptr
it contains the address of y therefore
assigns the value 1111 to y
DELETE pointers in the same scope/class in which they were created with the NEW keyword. You are already passing a pointer to the function and simply copying the reference. You need to free the pointer OUTSIDE the function: -
// The pointer.
-
int *MyPointer = NULL;
-
-
// Create a NEW int in memory.
-
MyPointer = new int;
-
-
// Pass the pointer to the function.
-
myFunction(MyPointer);
-
-
// DELETE the pointer.
-
delete MyPointer;
-
Only free up memory that you have allocated to the heap manually (using 'new' operator).
In your example, you haven't created anything on the heap, you are just throwing pointers to stack variables around.
Im using C, not C++ so i guess there won't be any NEW or DELETE keyword.
Quote :
"
so when you copy x to x_ptr
x_ptr = x;
it contains the address of y.. "
If i free *ptr_y from outside of the function, will it automatically free *ptr_x? or is ptr_x going to point to the previous address ptr_y held even though ptr_y is freed?
You have the wrong idea about how memory is manipulated in C/C++. First of all, in your program, you have no HEAP variables, so this information is useless in your program.
When you 'free' memory, a very low level operating system command is called. It tells the OS's memory management unit that the memory block that you freed can be used again. The pointers in your program are simply references, they have no physical tie-ins with the actual memory, they remain with the same value whether the memory has been freed or not. However, if you try using that pointer again, the memory might have been written over because the OS saw it as a free section of memory. If you 'copy' a pointer, you will have two pointers pointing to the same piece of memory. -
-
// Create some new HEAP memory.
-
int *Mem = new int;
-
-
// Give another pointer reference to the memory created.
-
int *Mem2 = Mem;
-
-
// Delete the memory.
-
delete Mem2;
-
Mem AND Mem2 STILL store the old memory LOCATION but as YOU deleted it, you wont be silly enough to try and use it again :)
Jason, I'm almost understanding it there but..
what if your
was declared inside a function? If we don't delete it, once we exited the function, there might not be a chance to delete it again.
and then put it in this scenario, we then delete Mem after we exit from the function.
at this stage, this would mean Mem2 is not cleaned since it used to point to Mem and we only deleted Mem.
Like I said, Mem2 and Mem both point to the same block of memory. If you call delete on any of those, and ANY time, the memory will be freed. Doesn't matter if you make another pointer point to the same memory within a function, it's just so you have reference to an object inside the function rather than passing all of the memory to the function, you just pass the address of the allocated memory.
The following program is perfectly fine, causing no memory leaks: -
-
int main()
-
{
-
// An integer (4 bytes) is allocated in heap memory.
-
int *Mem = new int;
-
-
// Call a function, passing the POINTER, not the
-
// actual int in memory, just a pointer to it.
-
FunctionCall(Mem);
-
-
// Good memory management says that you delete the
-
// allocated memory in the same scope that it was
-
// created.
-
delete Mem;
-
-
return 0;
-
}
-
-
// This function accepts a POINTER to some memory.
-
void FunctionCall(int *Mem)
-
{
-
// This is just a pointer, a MEMORY ADDRESS.
-
// NOTHING has been allocated on the heap when
-
// declaring this variable.
-
int *Mem2;
-
-
// Make the Mem2 POINTER POINT to the same block
-
// of memory that Mem points to. Once again,
-
// NOTHING new has been allocated in heap memory.
-
Mem2 = Mem;
-
-
// Change something in the memory location by
-
// de-referencing it with a '*'.
-
*Mem2 = 1234;
-
-
// At the end of this function, Mem and Mem2 will
-
// both return 1234 when de-referenced as they both
-
// point to the SAME block of memory.
-
-
// NO deletion is done here as the memory was
-
// allocated outside the function (this is what
-
// the function assumes).
-
}
-
I couldn't have explained it in more depth right now, i hope this helps you.
thanks alot jason..that's really straight to the point esp with all the comments on the code...i really appreciate it!
Sign in to post your reply or Sign up for a free account.
Similar topics
by: jack |
last post by:
Hi all,
Suppose I have a routine to find the maximum
of any *univariate* function f in the interval :
double f(double x);
double findmax(double (*func)(double), double a, double b);
Now I...
|
by: zx.zhangxiong |
last post by:
Dear all,
I'm puzzled about the usage of class member function. Any help would be
appreciated.
class Account {
...
|
by: Edd |
last post by:
Hello all,
I've made a data structure and an associated set of functions to enable me
to store a dynamically-sized array of elements of whatever data type I like.
Well that's the idea anyway......
|
by: glennpierce |
last post by:
Hi I was wondering if anyone knows of a method to achieve the creation of
events in c. currently I use a function pointer to call one callback.
However, I really need to map the function pointer or...
|
by: Peter Oliphant |
last post by:
Here is a simplification of my code. Basically, I have a class (A) that can
be constructed using a function pointer to a function that returns a bool
with no parameters. I then want to create an...
|
by: bluejack |
last post by:
Ahoy... before I go off scouring particular platforms for specialized
answers, I thought I would see if there is a portable C answer to this
question:
I want a function pointer that, when...
|
by: Kathir |
last post by:
In C,
I have a doubt about Function pointers.
Lets say ,
typedef void (*test_audit_proc_t)( int *t, int index, int instnb);
typedef struct a_index
{
|
by: Allen |
last post by:
Hi, I want to know How to create an associated array using map with
keys are string, values are function pointers with same arguments, but
each function belong to different class. The map need to...
|
by: ghulands |
last post by:
I am having trouble implementing some function pointer stuff in c++
An object can register itself for many events
void addEventListener(CFObject *target, CFEventHandler callback,
uint8_t...
|
by: Charlie |
last post by:
Hi All,
I am new to using swig/C++/python. I got some problem with function
pointers. I posted in swig-user, but got no response. So I forwarded
it here. You help is greatly appreciated.
...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
| |