473,756 Members | 6,098 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

IS this a proper way of freeing memory with free()

Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1 234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/

/** some stuff with p again**/


}
Thanks and Regards,
Raman Chalotra

Feb 1 '07
171 4919
Ryan Ply <th******@earth ling.netwrote:
Ian Collins <ia******@hotma il.comwrites:
Raman wrote:
Hi All,
>
Here is a small Code,
>
int main(void)
{
char *p=(char *) malloc(100);
How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?
strcpy(p,"Test1 234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/
>
It's completely undefined behaviour. Your toilet might explode. Don't
do it.
Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me.
I guess you refer to the "don't cast the return value of malloc()"
bit. It's explicitely stated in the errata for the book

http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

that

"The remark about casting the return value of malloc ("the proper
method is to declare ... then explicitly coerce") needs to be
rewritten. The example is correct and works, but the advice is
debatable in the context of the 1988-1989 ANSI/ISO standards.
It's not necessary (given that coercion of void * to ALMOSTANYTYPE *
is automatic), and possibly harmful if malloc, or a proxy for it,
fails to be declared as returning void *. The explicit cast can
cover up an unintended error. On the other hand, pre-ANSI, the cast
was necessary, and it is in C++ also."
How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.
Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Feb 1 '07 #11
Richard Heathfield wrote:
[...]
Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me.
[...]
See K&R's errata page, where they admit that the cast isn't such a great
idea after all (although of course it isn't exactly *wrong* provided you
remember <stdlib.h>).
[...]

Wasn't the first K&R written prior to adding "void" to the language?
Originally, malloc() et al returned "char *", which meant you had to
use a cast to point to other things.

I maintain code which still #define's VOID to either "void" or "char",
depending on whether the compiler supported void or not. I don't think
there are any current systems we have ported to which do not support
void.

On the other hand, there are still systems with compilers that do not
support function prototypes[1], so there is still the need for things
like:

#if HAS_PROTOTYPES
extern long SomeFunction(in t,int);
extern struct foo *AnotherFunctio n(struct bar *);
#else
extern long SomeFunction();
extern struct foo *AnotherFunctio n();
#endif
[1] Actually, the compiler recognizes the prototypes, and generates
an error stating that it doesn't support them. At least this
was the case the last time I used that system as recently as
about 2 years ago.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>

Feb 1 '07 #12
In article <52************ *@mid.uni-berlin.de>,
Jens Thoms Toerring <jt@toerring.de wrote:
>How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically ) would actually give me a warning if I didn't cast it.
>Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)
Or perhaps the system's stdlib.h didn't declare malloc()? Given the
existence of malloc.h on some systems, that wouldn't be too
surprising.

-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 1 '07 #13
Raman wrote:
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1 234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/

/** some stuff with p again**/


}
Others have said it, it's undefined behavior.

Here is a specific example. The numbers are specific to
one implementation I know of. Yours is most likely different.

On my example system, the heap is implemented by maintaining
the free memory blocks in a linked list.

Malloc goes through that list, trying to find a suitable block.
It may cut an existing one into fragments to avoid wasting
too much memory.

When a block is found, say at 0x12000, it gets unlinked from
the list and at the first location in the block the size is
stored. Malloc then returns a pointer to the first address
after that size (0x12004).

Free decrements the pointer by the correct amount (4 bytes),
retrieves the size and hooks the block back into the free list.

On such a system, your code isn't just a memory leak. In your
particular example, free would leak a small block of 10 bytes,
but also hook a free block starting at (p-4) into the free list,
with a size corresponding to the character sequence "3456".

This huge 'free' block is likely to overlap other free and used
memory. The next malloc could now hand out memory which is already
in use.

In other words, you are breaking the internal data structures
of the heap management, and after that anything may happen.

Kind regards,

Iwo

Feb 1 '07 #14
>>>>"CBF" == CBFalconer <cb********@yah oo.comwrites:

CBFAre there any reliable estimates as to the number of wood
CBFstove fires annually kindled by BullSchildt books? I have
CBFthe impression the value has been dropping for several years.
CBFThis may be correlated with the disappearance of Herbs from
CBFthe C book market.

Alas, I was in a bookstore earlier this week, and pride of place in
the C section, meager as it was, was given to _C: the Annotated
Reference_. At least K&R was also there.

(I was looking for the O'Reilly book on SVG, which I had to
special-order. Astounding how many self-evidently *bad* computer
books there are.)

Charlton

--
Charlton Wilbur
cw*****@chromat ico.net
Feb 1 '07 #15
Richard Tobin wrote, On 01/02/07 17:06:
In article <52************ *@mid.uni-berlin.de>,
Jens Thoms Toerring <jt@toerring.de wrote:
>>How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specificall y) would actually give me a warning if I didn't cast it.
>Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)

Or perhaps the system's stdlib.h didn't declare malloc()? Given the
existence of malloc.h on some systems, that wouldn't be too
surprising.
The the system's stdlib.h does not declare malloc then it is not C89
compliant and hence is covered by that Jens stated.
--
Flash Gordon
Feb 1 '07 #16
On 01 Feb 2007 08:29:02 -0800, in comp.lang.c , Ryan Ply
<th******@earth ling.netwrote:
>Ian Collins <ia******@hotma il.comwrites:
>Raman wrote:
char *p=(char *) malloc(100);

How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?
Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me.
If you're talking about the cast, the Errata list for the book refers
to this as having been a mistake. Also the book is twenty years old,
and C has moved on somewhat since then.
>How
many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically ) would actually give me a warning if I didn't cast it.
That must have been a C++ compiler. No actual ISO compliant C compiler
has ever been allowed to complain about it. Or else you forgot to
incude stdlib.h of course.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Feb 1 '07 #17
In article <bd************ @news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwro te:
>>>How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically ) would actually give me a warning if I didn't cast it.
>>Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)
>Or perhaps the system's stdlib.h didn't declare malloc()? Given the
existence of malloc.h on some systems, that wouldn't be too
surprising.
>The the system's stdlib.h does not declare malloc then it is not C89
compliant and hence is covered by that Jens stated.
I read Jens' statement as implying that the version of *gcc* must more
than a decade old. But gcc generally uses the system headers and
libraries, so it might have been the system rather than gcc that was
out-of-date.

-- Richard

--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 1 '07 #18
On Feb 1, 1:50 pm, Charlton Wilbur <cwil...@chroma tico.netwrote:
>>>"CBF" == CBFalconer <cbfalco...@yah oo.comwrites:

CBFAre there any reliable estimates as to the number of wood
CBFstove fires annually kindled by BullSchildt books? I have
CBFthe impression the value has been dropping for several years.
CBFThis may be correlated with the disappearance of Herbs from
CBFthe C book market.

Alas, I was in a bookstore earlier this week, and pride of place in
the C section, meager as it was, was given to _C: the Annotated
Reference_. At least K&R was also there.

Well, at least it's a cheap way of picking up a copy of the c89
standard. Well, except for that missing page...

Feb 1 '07 #19
"ro***********@ yahoo.com" <ro***********@ yahoo.comwrites :
On Feb 1, 1:50 pm, Charlton Wilbur <cwil...@chroma tico.netwrote:
>Alas, I was in a bookstore earlier this week, and pride of place in
the C section, meager as it was, was given to _C: the Annotated
Reference_. At least K&R was also there.

Well, at least it's a cheap way of picking up a copy of the c89
standard. Well, except for that missing page...
_C: The Annotated Reference_ != _The Annotated ANSI C Standard_
--
"Your correction is 100% correct and 0% helpful. Well done!"
--Richard Heathfield
Feb 1 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
22976
by: disco | last post by:
I am working on this example from a book "C Primer Plus" by Prata 4th edition - p. 672. There is no erata on this problem at the publisher's website. 1) Is it a violation of copyright laws to post example code from a book to a newsgroup? 2) The program crashes as it tries to free memory and I would like to know the best way to correct THIS section of the code. By assigning current = head, current now points to the first structure in...
12
3071
by: f.oppedisano | last post by:
Hi, i would like to allocate two structures making only one malloc call. So i do prt=malloc(sizeof(struct1)+sizeof(struct2)); After this operation i make two pointers one to the first struct (ptr1=ptr), the other to second struct(ptr2=ptr+sizeof(struct2)). These two pointer are later used by two threads in mutual exclusion so thread1 can't access ptr2 and thread2 can't access ptr1. At some time thread2 wants to free his part of memory but...
11
2298
by: Rodrigo Dominguez | last post by:
there are sometimes that I use third party libraries, I use some functions that returns char * or structs, etc. sometimes the memory that is returned by those libraries, when I try to free this memory whith the function free, it brokes my application, and sometimes it's ok, why? how do I realize when I have to free the memory that is allocated by third party libraries and why sometimes I don't have to free this memory? Thank you
6
2766
by: Fernando Cacciola | last post by:
Help me out here please: While watching Brad Abraham's MSDN TV talk about the Dispose pattern, refering to: public virtual void Dispose ( bool disposing ) { if ( disposing ) { <-- WHAT GOES HERE -->
4
36539
by: Atul Sureka | last post by:
Hi, I want to free the object memory in C# - like we do using 'delete' keyword in C++. Lets say I have an object of some class and I want to explicitly free the memory. C# do not have any free or delete keyword to do so. Also I don't want to wait for the GC to be called.
66
3699
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
9
3327
by: david | last post by:
I will past only two segments from the code it should be enough to see what I did wrong, I think I know there I made a mistake, but how to fix it I can not tell. This why I need help from you all. Main code: ---------------- /* duomenu rasymas i faila */ dst = fopen(argv, "w"); if (dst != NULL) { wordDBSize = sizeStack(wordDB);
11
2007
by: vivek | last post by:
Hello, I have a pointer to a main structure which again consists of structures, enums, char, int, float and again complex structures. When i free all the contents of the main structure, it takes me a lot of time (since i have to loop determining the data type and freeing it). Is there any idea to free all the contents of the structure in shortest possible time.
25
4727
by: Andreas Eibach | last post by:
Hi again, one of the other big woes I'm having... typedef struct perBlockStru /* (structure) Long words per block */ { unsigned long *lword; } lwperBlockStru_t;
0
9454
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9271
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9836
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9707
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7242
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6533
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3804
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2664
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.