C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 01-24-2009, 09:07 AM   #1
Registered User
 
Join Date: Jan 2009
Posts: 2
question about malloc() and free()

hi all,

I was reading through an old C tutorial and I tried this program on my pc:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main( )
{ struct animal 
  { char name[25];
    char breed[25];
    int age;
  } *pet1, *pet2;
  
  pet2 = malloc(sizeof(struct animal));
  strcpy(pet2->name,"Krystal");
  strcpy(pet2->breed,"German Shepard");
  pet2->age = 4;
  
     /*   now print out the data described above */

  printf("%s is a %s, and is %d years old.\n",pet2->name,pet2->breed, pet2->age); 
  pet1 = pet2;    /* pet1 now points to the same structure that pet3 points to                        */
  free(pet2);     /* this frees up one structure                */

 printf("%s is a %s, and is %d years old.\n",pet1->name,pet1->breed, pet1->age);
}
why is this program's output:

Krystal is a German Shepard, and is 4 years old.
is a German Shepard, and is 4 years old.

instead of what I supposed it should be?:

Krystal is a German Shepard, and is 4 years old.
is a German Shepard, and is years old.

why does the 4 remain after free() ?

thanks a lot
MissEileen is offline   Reply With Quote
Old 01-24-2009, 09:11 AM   #2
Mysterious C++ User
 
Join Date: Oct 2007
Posts: 14,099
Code:
main( )
{ struct animal 
  { char name[25];
    char breed[25];
    int age;
  } *pet1, *pet2;
First, main returns int: http://cpwiki.sourceforge.net/Implicit_main
Secondly, please avoid putting code on the opening {. It hurts readability, just as placing the } on anything but a new line.
And as for your question, it's undefined behavior. It's freed, alright, so whether or not that data is left is up to the OS. What YOU need to know is that you told the OS you no longer need it, so don't use it.
__________________
Using: Microsoft Windows™ 7 Professional (x64), Microsoft Visual Studio™ 2008 Team System
I dedicated my life to helping others. This is only a small sample of what they said:
"Thanks Elysia. You're a programming master! How the hell do you know every thing?"
Quoted... at least once.
Quote:
Originally Posted by cpjust
If C++ is 2 steps forward from C, then I'd say Java is 1 step forward and 2 steps back.
Elysia is offline   Reply With Quote
Old 01-24-2009, 09:18 AM   #3
Registered User
 
Join Date: Sep 2006
Posts: 2,502
The program assigns pet1 to pet2. Now you can free pet2, but that doesn't zero out the struct's memory values. It just marks that struc's memory as "available" for the heap.

Last edited by Adak; 01-24-2009 at 09:30 AM.
Adak is offline   Reply With Quote
Old 01-24-2009, 09:31 AM   #4
subminimalist
 
MK27's Avatar
 
Join Date: Jul 2008
Location: NYC
Posts: 3,944
Quote:
why does the 4 remain after free() ?
Because pet1 was not freed, and so now points to where pet2 did. Since pet1 was not allocated anything and pet2 was freed, this memory can be overwritten, but has not been because nothing else has happened. For example, with my compiler if I add the following:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

main( )
{ struct animal 
  { char name[25];
    char breed[25];
    int age;
  } *pet1, *pet2, *pet3;
char *this;
  
  pet2 = malloc(sizeof(struct animal));
  strcpy(pet2->name,"Krystal");
  strcpy(pet2->breed,"German Shepard");
  pet2->age = 4;
  
     /*   now print out the data described above */

  printf("%s is a %s, and is %d years old.\n",pet2->name,pet2->breed, pet2->age); 
  pet1 = pet2;    /* pet1 now points to the same structure that pet3 points to                        */
  free(pet2);     /* this frees up one structure                */

pet3=malloc(sizeof(struct animal));
  strcpy(pet3->name,"Ecstacy");
  strcpy(pet3->breed,"Golden Lab");
 printf("%s is a %s, and is %d years old.\n",pet1->name,pet1->breed, pet1->age);
     printf("pet3 age=%d\n",pet3->age)
}
The output is:
Krystal is a German Shepard, and is 4 years old.
Ecstacy is a Golden Lab, and is 4 years old.
pet3 age=4

pet1 (mysteriously and apparently) now points to pet3, and pet3 apparently has inherited pet2's age! This is beacause pet3 is stored in the same physical location as pet2 was -- the memory was freed for other use, not erased -- and pet1 still points to this location.

However, there is no guarantee the compiler (linker?) will actually do that, so it's not a technique to be used in programming.
__________________

Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS
MK27 is offline   Reply With Quote
Old 01-24-2009, 09:35 AM   #5
Mysterious C++ User
 
Join Date: Oct 2007
Posts: 14,099
The compiler does nothing. The operating system itself controls that aspect.
Also remember that your code is undefined and is not and never guaranteed to "inherit" some memory previously used.
__________________
Using: Microsoft Windows™ 7 Professional (x64), Microsoft Visual Studio™ 2008 Team System
I dedicated my life to helping others. This is only a small sample of what they said:
"Thanks Elysia. You're a programming master! How the hell do you know every thing?"
Quoted... at least once.
Quote:
Originally Posted by cpjust
If C++ is 2 steps forward from C, then I'd say Java is 1 step forward and 2 steps back.
Elysia is offline   Reply With Quote
Old 01-24-2009, 10:10 AM   #6
subminimalist
 
MK27's Avatar
 
Join Date: Jul 2008
Location: NYC
Posts: 3,944
Quote:
Originally Posted by Elysia View Post
The compiler does nothing. The operating system itself controls that aspect.
points taken
__________________

Accuracy and integrity mean nothing if you don't make it past the censors...PYTHAGORAS
MK27 is offline   Reply With Quote
Old 01-24-2009, 10:54 AM   #7
Registered User
 
Join Date: Jan 2009
Posts: 2
very clear now. thanks.
MissEileen is offline   Reply With Quote
Old 01-24-2009, 01:06 PM   #8
Kernel hacker
 
Join Date: Jul 2007
Location: Farncombe, Surrey, England
Posts: 15,686
Quote:
Originally Posted by Elysia View Post
The compiler does nothing. The operating system itself controls that aspect.
Also remember that your code is undefined and is not and never guaranteed to "inherit" some memory previously used.
To be pedantic, malloc and free are C runtime library functions, not OS functions [although they will usually have to interact with the OS to get blocks of memory, but since it's quite time-consuming to call the OS to get more memory, the heap management functions in the C library will normally call the OS to get a fairly large block of memory (say 64KB or more), and then split that into smaller pieces as it sees fit].

As to what happens when you free memory, it is indeed undefined, and "anything can happen". It gets even worse if you have multiple threads running in the system, because another thread may well allocate the memory that your thread is still using but has freed [or if you are writing drivers that free memory before the driver is finished with it, and another driver decides to allocate some memory - it can REALLY cause problems in this case. Imagine a file-system related driver allocating the same memory that I just freed for a write-buffer to a file, and my driver writing some data to the freed buffer - guess what: Your disk will need formatting pretty soon! (Don't ask how I know this )]

Never EVER rely on the content or behaviour of pointers that have been freed - very bad.

--
Mats
__________________
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
matsp is offline   Reply With Quote
Old 01-24-2009, 02:46 PM   #9
CSharpener
 
vart's Avatar
 
Join Date: Oct 2006
Posts: 5,242
Quote:
Never EVER rely on the content or behaviour of pointers that have been freed - very bad.
Just a few weeks ago I have fixed a bug like this
Code:
free(ptr);
*ptr = 0;
The bug was found due to crash that occured constanly on this line - but only on one computer during run of one specific scenario. Other computers and other scenarios were running other the place without a notice... I was lucky the crash occured in QA and not on the customer use
__________________
If I have eight hours for cutting wood, I spend six sharpening my axe.
vart is offline   Reply With Quote
Reply

Tags
free, malloc, output

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
malloc calloc and free -EquinoX- C Programming 27 03-26-2009 10:59 AM
Malloc - Free giving double free or corruption error andrew.bolster C Programming 2 11-02-2007 06:22 AM
(C, Malloc, Free) Help! Access violation and/or damage after normal block!! Raptor007 C Programming 12 06-24-2005 04:27 PM
Ask about free funtion using with malloc ooosawaddee3 C++ Programming 1 05-12-2002 04:43 PM
Malloc and Free..... heljy C Programming 5 04-14-2002 09:17 PM


All times are GMT -6. The time now is 09:28 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22