-1

Here is a part of my code which is creating the error.

int check(int size, char *string)
{
     if(condition)
     {             
         char *tempStr = (char*)calloc(size, sizeof(char));                                         
         /*
         some code here to put some string value to tempStr;
         */
         res += check(size,tempStr);
         free(tempStr);
     }
}

I have read and understood that the invalid next error occurs when we try to free memory that isn't available or when we try to free memory more than once(assuming this is my case).

How to solve the above error? Is the above method correct way to free memory when in recursion?

re3el
  • 735
  • 2
  • 12
  • 28

2 Answers2

3

As per the man page of free(), we can see, the signature of free() is

void free(void *ptr);

so, in your code,

free(size,tempStr);

is wrong. I fear, you might have missed stdlib.h header file itself. Which makes the next comment even more valid,


AFTER THE EDIT:

In the same man page, linked earlier, it is mentioned,

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs.

So, inside

     /*
     some code here;
     */

You cannot change the tempStr. That's all we can say, as per the code you've shown.

As per your comments,

"inserting a string into the tempStr "

My best bet is you're doing something like tempStr = "somesting" (an assignement, whereas you should be doing a strcpy()), which causes

  1. to lose your malloc()ed memory, creating memory leak.
  2. passing non-malloc()ed pointer to free, creating undefined behaviour.
Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I did not understand as to why will I lose my `malloc`ed memory when I insert a string into an array. – re3el Aug 21 '15 at 07:29
2

The free function in C only takes one parameter, which is the pointer to free.

By giving it a size, let's say 15, you ask free to free the memory at the address 15, which isn't malloc'd.

Don't forget to include stdlib.h so your compiler will know it takes only one parameter. (And it should correct a warning at the compilation time)

4rzael
  • 679
  • 6
  • 17