Free gives error
Consider the following two programs:
/*******开发者_如何学JAVA********correct: no error for this code **************/
#include <stdio.h>
#include <string.h>
int main()
{
char *p ,*q ;
p =(char *)malloc(10) ;
strcpy( p , "AB") ;
*p = '\0' ;
p++ ;
q = p ;
//*q = 32 ;
free(q) ;
return 0;
}
/*************code2 which gives error ********************/
#include <stdio.h>
#include <string.h>
int main()
{
int *p ,*q ;
p =(int *)malloc(10) ;
*p = 30 ;
p++ ;
q = p ;
*q = 32 ;
free(q) ;
return 0;
}
Can you explain why the first one works, but the second doesn't?
The code that works "correct" has undefined behavior. It's just (bad) luck that it works. Actually seeming to work is the worst that can happen as a result of UB(doesn't raise your alarm). The other code that doesn't work has undefined behavior as well.
You may call free
only on pointer returned by malloc
, realloc
or calloc
What the C standard says is that You cannot use free() for a normal pointers.It says free() function performs its action when it is used with the dynamic memory allocation functions like malloc(), calloc() and realloc().Even though if you try to use a free() by passing a normal pointer which is not involved with malloc(),calloc() and realloc(), it results undefined behaviour it may lead to core dumped error or crash and the code is working with your compiler because the compiler might be developed in a different way (example a student learning compiler) that code works even with the TURBO c but it really fails when you work on the cygwin or gcc compilers.I suggest you to work on cygwin and gcc compilers rather than other compilers because they give you very vast experience and knowledge even you can learn the concepts of Multithreading.
I believe both the codes are incorrect and should end up with crash. As when you do malloc
the OS keeps the initial address of the memory returned by malloc
and free
can only be called on the address given by malloc
.
精彩评论