[prog] Bug!!

Jimen Ching jching at flex.com
Sat Mar 1 21:55:10 EST 2003


On Sun, 2 Mar 2003, Sachin wrote:
>#include<stdio.h>
>#include<malloc.h>
>int main( )
> {
>   char *ptr;
>   ptr=(char *)malloc(20);
>   strcpy(ptr,"sachin");
>   printf ("\nThe value of ptr:%s and its address:%p\n",ptr,ptr);
>   free(ptr);
>   printf ("\nThe value of ptr:%s and its address:%p\n",ptr,ptr);
>   strcpy(ptr,"babu");
>   printf ("\nThe value of ptr:%s and its address:%p\n",ptr,ptr);
>}
>
>My program ,instead of printing segmentation fault ,faithfully prints
>both the strings.How it is possible?

Well, referencing a freed pointer produces "undefined" behavior.  Thus,
the C environment could print segmentation fault, or faithfully print the
contents.  My theory is that since the program is so small, the pointer is
still valid in the OS, so referencing it after free() was ok.  In a larger
application, I would expect the segmentation fault.  As a test, you might
try allocating lots of pointers, like around 100.  Then reference some of
the freed pointers.  The OS is likely to unmap some of those pointers, so
you would get the segmentation fault.

I actually, I tried another simple test.  I allocated 200000 bytes,
instead of the 20 bytes.  And the C environment segfaulted like I expect.
My theory is that, the Linux kernel is able to allocate 20 bytes from a
cache.  Freeing 20 bytes just returns it to the cache.  But allocating
200000 bytes requires a few pages from the VM (virtual memory) sub-system.
Thus, when you free 200000 bytes, the VM page is removed.  Future
reference to that page will cause a segfault.  I think a page is 4096
bytes.  Thus allocating anything larger than this should produce the
segfault.

Good luck.

--jc

P.S.  I'm not sure if the code above is supposed to be ANSI C.  But
malloc.h is not an ANSI library header.  malloc is prototyped in stdlib.h.
Just thought I mention that.  ;-)

-- 
Jimen Ching (WH6BRR)      jching at flex.com     wh6brr at uhm.ampr.org


More information about the Programming mailing list