Click here to Skip to main content
15,915,083 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
my task is create a memory for pointer in dynamic library

and free up the memory of allocated in the main function..

i can do create and free the memory in same side..
but i can't perform the operation in vice versa..


my library function code:

DYNAMICLIB_API int* aa1(void)
{
    int *a1;
    a1=(int*)malloc(sizeof(int));
    printf("Interger created\n");
    printf("bye");
    printf("good");
    printf("memory created");
    free(a1);
    return a1;
}

my main function code:
int main(int argc, char* argv[])
{
    int *a1;
    a1=aa1();
    printf("Hello World!\n");
    free(a1);
    return 0;
}



the free function provide the run time error.. can you help me

[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 5-Jul-11 1:06am
v2
Comments
Prerak Patel 5-Jul-11 7:11am    
What is the error?

1 solution

I'm not surprised - you are returning a pointer to memory you have already freed:
free(a1);
return a1;

Then, you try to free it again!

Bad idea - never, ever return a pointer to anything unless you allocated it, and haven't freed it. That includes things like this:
int* GetBadPointer(void)
   {
   int i = 76;
   return &i;
   }
It will always blow up in your face at some point, normally when you don't expect it, unless you are very careful with your pointers!
 
Share this answer
 
Comments
@BangIndia 5-Jul-11 7:17am    
sorry sir..

DYNAMICLIB_API int* aa1(void)
{
int *a1;
a1=(int*)malloc(sizeof(int));
printf("Interger created\n");
printf("bye");
printf("good");
printf("memory created");
return a1;
}
now also not coming the output . what i do.. now
OriginalGriff 5-Jul-11 10:25am    
If I try your code through a boring ANSI C compiler I have to remove the DYNAMICLIB_API and it works fine.

What is the DYNAMICLIB_API bit and have your tried to remove it?
@BangIndia 6-Jul-11 0:54am    
i create a dynamic library for creating the memory..
and i use the main function to free that memory.

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