473,414 Members | 1,709 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

do i need to free local function pointer?

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?

Expand|Select|Wrap|Line Numbers
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4.  
  5. void myfunction(int *x)
  6. {
  7.     int *x_ptr = NULL;
  8.  
  9.     x_ptr = x;
  10.  
  11.     *x_ptr = 1111;
  12.  
  13.     printf("%myfunction local pointer is %d\r\n", *x_ptr);
  14.  
  15.  
  16. }
  17.  
  18. int main(int argc, char* argv[])
  19. {
  20.  
  21.     int y = 5;
  22.     int *ptr_y;
  23.  
  24.     ptr_y = &y;
  25.  
  26.     printf("y starts with %d\r\n", y);
  27.  
  28.     myfunction(ptr_y);
  29.  
  30.     y = 6;
  31.  
  32.     myfunction(ptr_y);
  33.  
  34.     printf("at the end, y is %d\r\n", y);
  35.     return 0;
  36. }
  37.  
  38.  
Feb 16 '11 #1

✓ answered by Jason Mortmer

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:

Expand|Select|Wrap|Line Numbers
  1.  
  2. int main()
  3. {
  4.    // An integer (4 bytes) is allocated in heap memory.
  5.    int *Mem = new int;
  6.  
  7.    // Call a function, passing the POINTER, not the
  8.    // actual int in memory, just a pointer to it.
  9.    FunctionCall(Mem);
  10.  
  11.    // Good memory management says that you delete the
  12.    // allocated memory in the same scope that it was
  13.    // created.
  14.    delete Mem;
  15.  
  16.    return 0;
  17. }
  18.  
  19. // This function accepts a POINTER to some memory.
  20. void FunctionCall(int *Mem)
  21. {
  22.    // This is just a pointer, a MEMORY ADDRESS.
  23.    // NOTHING has been allocated on the heap when 
  24.    // declaring this variable.
  25.    int *Mem2;
  26.  
  27.    // Make the Mem2 POINTER POINT to the same block
  28.    // of memory that Mem points to. Once again, 
  29.    // NOTHING new has been allocated in heap memory.
  30.    Mem2 = Mem;
  31.  
  32.    // Change something in the memory location by
  33.    // de-referencing it with a '*'.
  34.    *Mem2 = 1234;
  35.  
  36.    // At the end of this function, Mem and Mem2 will
  37.    // both return 1234 when de-referenced as they both
  38.    // point to the SAME block of memory.
  39.  
  40.    // NO deletion is done here as the memory was
  41.    // allocated outside the function (this is what
  42.    // the function assumes).
  43. }
  44.  
I couldn't have explained it in more depth right now, i hope this helps you.

7 12514
horace1
1,510 Expert 1GB
on entry to myfunction() pointer x contains the address of y in main()
Expand|Select|Wrap|Line Numbers
  1. void myfunction(int *x)
so when you copy x to x_ptr
Expand|Select|Wrap|Line Numbers
  1.   x_ptr = x;
  2.  
it contains the address of y therefore
Expand|Select|Wrap|Line Numbers
  1.     *x_ptr = 1111;
  2.  
assigns the value 1111 to y
Feb 16 '11 #2
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:

Expand|Select|Wrap|Line Numbers
  1. // The pointer.
  2. int *MyPointer = NULL;
  3.  
  4. // Create a NEW int in memory.
  5. MyPointer = new int;
  6.  
  7. // Pass the pointer to the function.
  8. myFunction(MyPointer);
  9.  
  10. // DELETE the pointer.
  11. delete MyPointer;
  12.  
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.
Feb 16 '11 #3
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?
Feb 16 '11 #4
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.

Expand|Select|Wrap|Line Numbers
  1.  
  2. // Create some new HEAP memory.
  3. int *Mem = new int;
  4.  
  5. // Give another pointer reference to the memory created.
  6. int *Mem2 = Mem;
  7.  
  8. // Delete the memory.
  9. delete Mem2;
  10.  
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 :)
Feb 16 '11 #5
Jason, I'm almost understanding it there but..

what if your

Expand|Select|Wrap|Line Numbers
  1. int *Mem2 = Mem;
  2.  
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.
Feb 18 '11 #6
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:

Expand|Select|Wrap|Line Numbers
  1.  
  2. int main()
  3. {
  4.    // An integer (4 bytes) is allocated in heap memory.
  5.    int *Mem = new int;
  6.  
  7.    // Call a function, passing the POINTER, not the
  8.    // actual int in memory, just a pointer to it.
  9.    FunctionCall(Mem);
  10.  
  11.    // Good memory management says that you delete the
  12.    // allocated memory in the same scope that it was
  13.    // created.
  14.    delete Mem;
  15.  
  16.    return 0;
  17. }
  18.  
  19. // This function accepts a POINTER to some memory.
  20. void FunctionCall(int *Mem)
  21. {
  22.    // This is just a pointer, a MEMORY ADDRESS.
  23.    // NOTHING has been allocated on the heap when 
  24.    // declaring this variable.
  25.    int *Mem2;
  26.  
  27.    // Make the Mem2 POINTER POINT to the same block
  28.    // of memory that Mem points to. Once again, 
  29.    // NOTHING new has been allocated in heap memory.
  30.    Mem2 = Mem;
  31.  
  32.    // Change something in the memory location by
  33.    // de-referencing it with a '*'.
  34.    *Mem2 = 1234;
  35.  
  36.    // At the end of this function, Mem and Mem2 will
  37.    // both return 1234 when de-referenced as they both
  38.    // point to the SAME block of memory.
  39.  
  40.    // NO deletion is done here as the memory was
  41.    // allocated outside the function (this is what
  42.    // the function assumes).
  43. }
  44.  
I couldn't have explained it in more depth right now, i hope this helps you.
Feb 18 '11 #7
thanks alot jason..that's really straight to the point esp with all the comments on the code...i really appreciate it!
Feb 18 '11 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
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...
3
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 { ...
11
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......
1
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...
6
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...
23
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...
1
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 {
9
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...
7
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...
5
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. ...
0
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
0
BarryA
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...
1
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...
0
marktang
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,...
0
Oralloy
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,...
0
tracyyun
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...
0
agi2029
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,...
0
isladogs
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...
0
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.