Is there anything wrong in the following code : - Because I am freeing the local variable tt, will it affect 'str' variable in the main function. will there be any memory leaks for bulk requests?
You are not allowed to continue to use malloc'ed space after you free'd it. Lots of people do that, but it is not legal. You program might happen to work with some malloc libraries. But probably not after both a free() followed by another malloc() as implied by your "bulk" remark. But on the bright side, no, this will not result in a memory leak. I have seen this stuff done a lot. Usually someone allocates a bunch of stuff and the beginning of a function, immediately frees it all, and continues to use it during the function. The idea is that the space is then almost like it resides in the stack. After a return, another function can use malloc and thus reuse the space that was freed. You are upping the ante by trying to use the freed space after a return. So my advice is don't do stuff like this.
You were on the right track. Just don't invoke free(). At least not until you are finished with the string. If you have more than a predictably few such strings, you must free each string when you are done or you will have that memory leak you were worried about.
I think you need to create a string at run time .And if that is the case you could use following code
int prep_string(char *);
int main()
{
char *str; // The dynamicallly allocated string u could use it like any other string
// Like str[30] ,str [i]is valid since it is charachter string
if(prep_string(str) == -1)
//code to handle not enough memory condition
// Now use the str as any other charachter string
return 0;
}
int prep_string(char *str)
{
int size ;
printf("\nEnter the size of the string ");
scanf("%d",&size);
str =(char *) malloc(size * sizeof(char));
if(str == NULL)
// Not enough memory to satisfy the request
return -1;
else
return 0;
}
I think the following serves ur purpose if any thing again is wrong with that pls correct me , actually i just typed that code in a hurry that's the reason..
char * prep_string();
int main()
{
char *str; // The dynamicallly allocated string u could use it like any other string
// Like str[30] ,str [i]is valid since it is charachter string
if( (str =prep_string() ) == NULL)
//code to handle not enough memory condition
else
// Now use the str as any other charachter string
return 0;
}
char * prep_string()
{
int size ;
printf("\nEnter the size of the string ");
scanf("%d",&size);
str =(char *) malloc(size * sizeof(char));
if(str == NULL)
// Not enough memory to satisfy the request
//Place the code to handle the situation
return NULL;
else
return str; // Now both pointers point to the same location
}