On 9/9/2012 9:14 AM, vaysagekv wrote:
> I have a function like below.The program has compiled without any errors
> .But when I run it I am getting Error like this --->fibBigNumbers(186
> malloc: *** error for object 0x100000ee2: pointer being freed was not
> allocated
> *** set a breakpoint in malloc_error_break to debug
> 021Abort trap.
>
> Program:
> void fibonacci(void)
> {
> static char* i = "1";
> static char* j = "1";
>
> char* fib = addBigNumbers(i,j);
> printf("\n%s",fib);
>
> char* temp = i;
> i=j;
> j=fib;
> if (!strcmp(temp,"1"))
> {
> free(temp);
> temp = NULL;
> }
> }
You must not free() memory you did not obtain from malloc()
(or calloc() or realloc()). When your code executes free(temp),
`temp' points to the "1" that initialized `i'. The memory
holding that string was not obtained from malloc(), so you must
not try to free() it.
Aside: It is possible that the !strcmp(temp,"1") test is
confusing you. You may have intended to call free() only when
`temp' points to something other than "1", but the actual code
does exactly the opposite: If `temp' points to something equal
to "1", strcmp(temp,"1") returns zero to say that the strings
are equal. Then the `!' converts that zero to one, which is
"true" for the `if' test. A hasty reading of `if(!strcmp(...))'
seems to say "Do something if the strings are not equal," but
in fact it says "Do something if the strings *are* equal." For
this reason (among others), I suggest you stop using the `!strcmp'
form and write `if(strcmp(...) == 0)' or `if(strcmp(...) != 0)'
to make your intent clearer.
--
Eric Sosman
d
"The speed at which the system fails is usually not important."