473,722 Members | 2,161 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 #1
171 4893
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.

--
Ian Collins.
Feb 1 '07 #2
Raman wrote:
char *p=(char *) malloc(100);
char *p = malloc(100 * sizeof *p);

Don't cast the return value from malloc().
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
****/
Completely invalid. free() expects a pointer originally returned from one of
the other allocation functions (calloc, malloc, realloc).

NAME
free - free allocated memory

SYNOPSIS
#include <stdlib.h>

void free(void *ptr);

DESCRIPTION
The free() function shall cause the space pointed to by ptr to be
deallocated; that is, made available for further allocation. If ptr is a null
pointer, no action shall occur. Otherwise, if the argument does not match a
pointer earlier returned by the calloc(), malloc(), or realloc() function, or
if the space has been deallocated by a call to free() or realloc(), the
behavior is undefined.

Any use of a pointer that refers to freed space results in undefined
behavior.

Feb 1 '07 #3
Ian Collins 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?
Basically forever. As long as it's still in books that people read - they'll
keep doing it.
Feb 1 '07 #4
Christopher Layne wrote:
Ian Collins 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?


Basically forever. As long as it's still in books that people read - they'll
keep doing it.
So maybe book burning isn't such a bad idea after all.

--
Ian Collins.
Feb 1 '07 #5
"Raman" <ra***********@ gmail.comwrote in message
news:11******** *************@s 48g2000cws.goog legroups.com...
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1 234567890");
p=p+10;
free(p);
Problems:

a)You don't test the return value from malloc() to be sure malloc() is able
to grant the memory. There can be some reasons why not ... you should
always test.

b)You may only free() pointers returned by malloc() and friends. The
behavior is undefined. Most likely it will wreck(*) the state of the
runtime library.

(*)The reason for this is that memory allocation is written to be efficient,
and assumes a correct client.

--
David T. Ashley (dt*@e3ft.com)
http://www.e3ft.com (Consulting Home Page)
http://www.dtashley.com (Personal Home Page)
http://gpl.e3ft.com (GPL Publications and Projects)
Feb 1 '07 #6
Raman wrote:
>
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**/
}
Is here undefined behaviour, because you freed a pointer not
created by malloc. Incidentally, the cast is not required, and bad
because you suppressed the error report from the compiler, due to
failure to #include <stdlib.h>.

--
<http://www.cs.auckland .ac.nz/~pgut001/pubs/vista_cost.txt>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 1 '07 #7
Ian Collins wrote:
Christopher Layne wrote:
>Ian Collins 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?

Basically forever. As long as it's still in books that people read
- they'll keep doing it.

So maybe book burning isn't such a bad idea after all.
Are there any reliable estimates as to the number of wood stove
fires annually kindled by BullSchildt books? I have the impression
the value has been dropping for several years. This may be
correlated with the disappearance of Herbs from the C book market.

--
<http://www.cs.auckland .ac.nz/~pgut001/pubs/vista_cost.txt>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews

Feb 1 '07 #8
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. 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.

Thats my thoughts on the matter.

Ryan -
Feb 1 '07 #9
Ryan Ply said:
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.
Yes, but K&R remembered to #include <stdlib.h>, didn't they? And in any
case, he wasn't talking about the cast. he was talking about the free().

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>).
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.
It was probably telling you, indirectly, that you forgot to #include
<stdlib.h- casting malloc, however, does *not* solve the problem gcc was
warning you about; it merely hides the warning message.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 1 '07 #10

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

Similar topics

5
22975
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
3068
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
2297
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
3688
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
9
3326
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
2004
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
4719
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
8863
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
8739
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,...
0
9238
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9157
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
9088
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...
0
8052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4762
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3207
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
2
2602
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.