Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Questions about free() 1

Status
Not open for further replies.

mattias1975

Programmer
Jul 26, 2004
36
0
0
SE
Hello!

Is there any rule when to use the function free()?
Some times when i use it i get the message
"Segmentation fault" from the compiler. Why?
 
> Is there any rule when to use the function free()?
You call it exactly ONCE for each result returned by malloc / calloc / realloc

> "Segmentation fault" from the compiler. Why?
It's not from the compiler, its from the operating system stopping your errant program from causing any more damage.

It usually means you messed up with the memory you got from malloc - example
Code:
char *p = malloc( 10 );     /* 9 chars and a \0 max */
strcpy( p, "hello world" ); /* this is too much!!! */
What happens next is anyone's guess.

At some random point in the future (perhaps never), there is a chance that any following call to malloc or free will crash in a manner you describe. The failure to crash of course does not mean that the program is bug free.

Of course the real trick is figuring out the cause (where the memory was corrupted) as opposed to the effect (where the problem was noticed in the form of a segfault).

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top