[prog] Bug!!
Sachin
sachinr at vsnl.in
Sun Mar 2 23:35:59 EST 2003
Dear Mr.Ching,
10
bytes or pow(10,100) bytes , coudn't the free function assign a NULL to the
pointer to memory position it freed.Why should it be left as undefined
behaviour?
Sachin
----- Original Message -----
From: Jimen Ching <jching at flex.com>
To: Prgm&&Linux <programming at linuxchix.org>
Sent: Sunday, March 02, 2003 12:25 PM
Subject: Re: [prog] Bug!!
> 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
> _______________________________________________
> Programming mailing list
> Programming at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/programming
>
More information about the Programming
mailing list