Click here to Skip to main content
15,891,633 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

This is my coding for creating dynamic link library function to allocate memory for a pointer value in main function and pass it to dynamic library function and free the pointer there in library..

MAIN FUNCTION:
int main(int argc, char* argv[])
{
    int *p=NULL;
    p=new int(100);
    printf("\nMemory allocated for pointer 1 and size is %d\n",p);
    fn1(p);
    return 0;
}

LIBRARY FUNCTION:
DYNLIB_API void fn1(int *p)
{
	printf("\nThis is lib func 1\n");
	free(p);
	printf("\npointer 1 memory cleared and size is %d\n",p);
}

The code successfully compiled. But during run-time I got an error to abort the program while it executes the free() line in library function.

How to clear it?

Please help me...
Posted
Updated 6-Jul-11 3:49am
v2
Comments
Eugen Podsypalnikov 6-Jul-11 9:26am    
Already tried to use delete and not free ? :)
IT-NEWBIE 6-Jul-11 9:34am    
I tried delete instead of free(). But it is not working.
What shall I do?
Eugen Podsypalnikov 6-Jul-11 9:39am    
Then try to modify your free-function to the following form :) :

DYNLIB_API void fn1(int **p)
{
if (p) {
delete *p;
*p = NULL;
}
}

...and its call :

int main(int argc, char* argv[])
{
int *p=NULL;
p=new int(100);
fn1(&p);
return 0;
}

Ouch!

When you use new to get some memory you MUST use delete to free it.

If you want to use free, you must get the memory using malloc.

So in your case... you are doing it in the wrong way mixing memory handling techniques.

Hope this helps.

Oh: and please, take a look at this link[^].
 
Share this answer
 
v3
Comments
Albert Holguin 6-Jul-11 9:49am    
yes, but in addition see cpallini's solution...
Joan M 6-Jul-11 9:52am    
Of course... I can see that it is not a good design...
Sergey Alexandrovich Kryukov 6-Jul-11 12:28pm    
Good catch, a 5. (However this mistakes was the first came to my mind; way too predictable behavior of the student developer :-)
--SA
Joan M 6-Jul-11 12:31pm    
Thank you SAKryukov!
Don't do that (allocate and deallocate in different modules) see Allocating and freeing memory across module boundaries[^].
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 6-Jul-11 12:26pm    
Good point, my 5. I also suggested deallocation only in the same stack frame as allocation in case of stack variable or allocation in constructor with deallocation in destructor (or their logical equivalents).
--SA
Something else, although this wasn't your question, I think is interesting to mention as well; this statement:
printf("\nMemory allocated for pointer 1 and size is %d\n",p);


...will print the memory location of p. Judging from the text, that is not what you want? The number of elements could be printed like so:
printf("\nNumber of elements in p: %d\n",*p);


The memory allocated is more than the number of elements, since the 100 integers are larger than 1 byte each and there is additional information (such as number of elements) stored.
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 6-Jul-11 12:29pm    
Ha-ha, so many failures in such a tiny code fragment. My 5 for the catch.
--SA
Stefan_Lang 7-Jul-11 11:46am    
Actually, the first print() would require sizeof(p)/sizeof(p[0]), whereas the second won't work, since the passed pointer does not hold any information about the size of the array.
P.S.: and even the first won't work, since the type of p in main() is pointer to int, not int[]...
[no name] 7-Jul-11 11:55am    
I'm not sure I understand what you mean? If you print p directly, the result is a memory location, e.g. 3350688.
Printing *p will output 100.
Stefan_Lang 7-Jul-11 11:59am    
Sorry, my bad, I misread new int(100) for new int[100]. Just my sloppy reading skills... ;)
Some hints:
1. See solution 1 and 2 about the two memory related errors.

2. You allocate memory for just one integer with the statement
int*p = new int(100);
The round paranthesis indicate that the value passed is used as an initializer, i. e. the int you allocated will be initialized with the value 100. Was that your intention? If you wanted to allocate an array of 100 integers, then you must use square brackets, like this:
int* p = new int[100];


If that was indeed your intention, in order to deallocate p properly, you must use
delete [] p;


3. It is generally good design to deallocate memory at the 'same location' where the allocation occurs. In case of classes, this can be anywhere in the class (usually a dedicated cleanup function), but in case of global functions it should preferably be inside the very same function. The main reason is exception safety: if anything goes amiss in your function, or in a function it calls, and it throws an exception, then no other function will ever know about the memory you allocated and failed to deallocate - therefore you must are responsible to deallocate the memory in case an exception occurs after successfully allocating it.

4. p is just a pointer and holds no size information, so I don't know how you intend to divine the 'Number of Elements' in your lib function from it. Not to mention that you access p after freeing it, so if this text refers to the number originally stored in p, trying to access that number will result in a runtime error!

5. A little pet-peeve of mine: don't use 'magic numbers', i. e. integer constants with arbitrary values. I realize this was just a small example code, but as a rule of thumb, it's always a good idea to e. g. store array sizes in a variable, or, prefarably, a constant, in case this value is needed again.

Example code:
const int ARRAY_SIZE = 100;
int main(...) {
   int result(0); // return value, see below
   int* p = new int[ARRAY_SIZE];
   // skipping your printf as I'm confused as to what it is supposed to print
   try { // fn1 might throw, so we must catch exceptions
      fn1(p, ARRAY_SIZE);
      delete [] p; // clean up
   }
   catch(...) { // catch all
      delete [] p; // clean up
      result = 1; // handle exception: return a value != 0
   }
   return result;
}

void fn1(int* p, size_t size) {
   puts("This is lib func"); // much faster than printf, and will add line break
   // do something with p, but don't deallocate it!
}

Ok, I admit that making this excepton safe is way beyond your question, but I thought I added it as a demonstration on why you should deallocate memory in the same function (or class) where you allocate it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900