473,769 Members | 2,501 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 4944
Yevgen Muntyan said:
Richard Heathfield wrote:
<snip>
>>
I fail to see why:

p = ALLOC_A_THING(f oo);

is more convenient than:

p = malloc(sizeof *p);

You fail to see, I don't. I like ALLOC_A_THING because
it describes the intent and hides the actual memory
allocation.
No, it doesn't, at least no more than malloc does. And even if it did,
which it doesn't, you still don't need the cast.
How
about custom_allocato r_here() function?
Yeah, you wouldn't need a cast there either.

<snip>
>>Or

#define FOO_NEW() ((Foo*) malloc (sizeof (Foo))) // *must* cast here

Why? The cast doesn't do any good,

It saves your butt if you change type,
So let me get this straight - you're saying that if you're daft enough
to use the type in the sizeof, you have to write some otherwise
unnecessary code to give the compiler a fighting chance of warning you
about your daft decision, and only at the risk of suppressing another
warning about your daft decision? Yeah, that's true - constructing
daftness is not difficult in C, or in any language. So?

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

<snip>
It's easy to write lot of C code which is valid C++. You have to
apply casts to return value of malloc though.
It's *pointless* to write lots of C code which is valid C++. If you
can't take advantage of C++'s non-C features, why bother using it? And
if you can, then it's not compilable in C. And malloc makes for bad C++
programs, on the whole.
>>>2) C++ defines mechanisms to interface to C code that has been
compiled as C code.
>>And I am talking about compiling *C* code with *C++* compiler.

If you're compiling it with a C++ compiler, its C++ code. It may look
like C, it may also compile as C, but its C++, and probably badly
written C++ at that.

Okay, let's use this term: "C code which is intended to be compiled
both with C and C++ compilers".
Ah, you mean "bad code" (unless your name is P J Plauger, which it
isn't).
I mean "C code" by "C code", i.e.
the code which is C according to C standard and is compilable with
C compiler in conforming mode. Not sure it's strict enough, but hope
you get the idea (which you already got anyway, I believe).
And no, C code doesn't become C++ code because you feed it to g++,
even if C++ folks think it is :)
Right. Instead, if it's a *good* C program, it becomes a raw material
which the compiler uses to produce diagnostic messages. If it's a bad
or trivial C program, it might also be a valid C++ program. Such
multi-language programs are few and far between, but they do exist.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 9 '07 #112
Yevgen Muntyan <mu************ ****@tamu.eduwr ote:
Mark McIntyre wrote:
On Thu, 08 Feb 2007 13:14:44 -0600, in comp.lang.c , Yevgen Muntyan
<mu************ ****@tamu.eduwr ote:

Flash wrote
>1) In C++ there are better methods than using malloc to get memory
You lose compatibility with C then ;)
Yes, people who think C and C++ are compatible often do seem to prefer
sloppy ill-defined compatibility over formal but slightly harder to
use compatibility. Smiley noted.

It's easy to write lot of C code which is valid C++. You have to
apply casts to return value of malloc though.
That's what Mark said: sloppy.

Richard
Feb 9 '07 #113
"matevzb" <ma*****@gmail. comwrote:
On Feb 8, 11:51 pm, CBFalconer <cbfalco...@yah oo.comwrote:
matevzb wrote:
I tend to disagree on this one. If you change the type of "ptr"
you *should* examine *all* the places where "ptr" was used anyhow
(not just the line with malloc). If you don't, that's promoting
bad habits and that may bite harder than the x*sizeof(<type> ). I
personally always use the latter and have never had any trouble
with it.
Not necessary. If you have avoided unnecessary casts, the compiler
will point out any harmful type mismatches.
No, it won't in case of void *. A hypothetical case:
#include <stdlib.h>
#include <string.h>

typedef enum
{
SHORT = 0,
LONG = 1
} mytype;

int
fcn (void *array, mytype type, size_t size)
{
void *ptr;

switch (type)
{
case SHORT:
ptr = malloc (size * sizeof(short));
You didn't read the construct you're criticising, did you? You didn't
even read the reason why that construct is better, because here you're
demonstrating exactly why it is better than this code.

Again:

ptr=malloc(num * sizeof *ptr);

is always less likely to break than

ptr=malloc(num * sizeof(type));

If you choose to break that by using void * for everything and then
casting to random types, that's your problem, and it demonstrates
exactly nothing about the need to check anything in well-written C.

Richard
Feb 9 '07 #114
Richard Heathfield wrote:
Yevgen Muntyan said:

<snip>

>>It's easy to write lot of C code which is valid C++. You have to
apply casts to return value of malloc though.


It's *pointless* to write lots of C code which is valid C++. If you
can't take advantage of C++'s non-C features, why bother using it? And
if you can, then it's not compilable in C. And malloc makes for bad C++
programs, on the whole.
It's not pointless if you are using C++ for hardware simulations to test
your C drivers.

--
Ian Collins.
Feb 9 '07 #115
Ian Collins said:
Richard Heathfield wrote:
>Yevgen Muntyan said:

<snip>

>>>It's easy to write lot of C code which is valid C++. You have to
apply casts to return value of malloc though.


It's *pointless* to write lots of C code which is valid C++. If you
can't take advantage of C++'s non-C features, why bother using it?
And if you can, then it's not compilable in C. And malloc makes for
bad C++ programs, on the whole.
It's not pointless if you are using C++ for hardware simulations to
test your C drivers.
If you're using C++ for the hardware simulations, you're using C++, not
C.

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

>>Richard Heathfield wrote:
>>>Yevgen Muntyan said:

<snip>

It's easy to write lot of C code which is valid C++. You have to
apply casts to return value of malloc though.
It's *pointless* to write lots of C code which is valid C++. If you
can't take advantage of C++'s non-C features, why bother using it?
And if you can, then it's not compilable in C. And malloc makes for
bad C++ programs, on the whole.

It's not pointless if you are using C++ for hardware simulations to
test your C drivers.


If you're using C++ for the hardware simulations, you're using C++, not
C.
The driver code is C.

--
Ian Collins.
Feb 9 '07 #117
Ian Collins said:
Richard Heathfield wrote:
>Ian Collins said:
>>>Richard Heathfield wrote:
Yevgen Muntyan said:

>It's easy to write lot of C code which is valid C++. You have to
>apply casts to return value of malloc though.

It's *pointless* to write lots of C code which is valid C++. [...]

It's not pointless if you are using C++ for hardware simulations to
test your C drivers.

If you're using C++ for the hardware simulations, you're using C++,
not C.
The driver code is C.
Fine, in which case it isn't C++, so you don't need the cast on malloc.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 9 '07 #118
On Feb 9, 5:39 am, "Bill Pursell" <bill.purs...@g mail.comwrote:
On Feb 9, 1:11 am, "matevzb" <mate...@gmail. comwrote:
On Feb 8, 11:51 pm, CBFalconer <cbfalco...@yah oo.comwrote:mat evzb wrote:
I tend to disagree on this one. If you change the type of "ptr"
you *should* examine *all* the places where "ptr" was used anyhow
(not just the line with malloc). If you don't, that's promoting
bad habits and that may bite harder than the x*sizeof(<type> ). I
personally always use the latter and have never had any trouble
with it.
Not necessary. If you have avoided unnecessary casts, the compiler
will point out any harmful type mismatches.
No, it won't in case of void *. A hypothetical case:
#include <stdlib.h>
#include <string.h>
typedef enum
{
SHORT = 0,
LONG = 1
} mytype;
int
fcn (void *array, mytype type, size_t size)
{
void *ptr;
switch (type)
{
case SHORT:
ptr = malloc (size * sizeof(short));
memcpy (ptr, array, size * sizeof(short));
break;
case LONG:
ptr = malloc (size * sizeof(long));
memcpy (ptr, array, size * sizeof(long));
break;
default:
return -1;
}
return 0;
}
int
main (void)
{
long *ptr = malloc (10 * sizeof *ptr);
memset (ptr, 1, 10 * sizeof *ptr);
fcn (ptr, LONG, 10);
return 0;
}
If "ptr" in main() is changed from "long *" to "short *", there will
be no warning (and no casts were used). There will be a bug lurking
however.

This bug is caused by a design flaw in fcn. Change the
prototype so that the call is fcn(ptr, sizeof *ptr, 10) and
the problem is gone. Be in the habit of casting malloc
and hand editing your entire code base whenever you
change a type, and you will probably not notice the
design flaw. Be in the habit of not casting malloc and
not editing your code base regularly, and the design
flaw will be obvious early.
You could put it that way. Unfortunately, I have to use a function
very similar to the abovementioned fcn() and it's part of an external
library on which I have no influence whatsoever (the function is used
for packing parameters for RPC calls). I don't use any unnecessary
casts, but using sizeof *ptr brings me no benefits. Perhaps it's a
design flaw, but I prefer to call it reality.
--
WYCIWYG - what you C is what you get

Feb 9 '07 #119
On Feb 9, 8:27 am, r...@hoekstra-uitgeverij.nl (Richard Bos) wrote:
"matevzb" <mate...@gmail. comwrote:
On Feb 8, 11:51 pm, CBFalconer <cbfalco...@yah oo.comwrote:
matevzb wrote:
I tend to disagree on this one. If you change the type of "ptr"
you *should* examine *all* the places where "ptr" was used anyhow
(not just the line with malloc). If you don't, that's promoting
bad habits and that may bite harder than the x*sizeof(<type> ). I
personally always use the latter and have never had any trouble
with it.
Not necessary. If you have avoided unnecessary casts, the compiler
will point out any harmful type mismatches.
No, it won't in case of void *. A hypothetical case:
#include <stdlib.h>
#include <string.h>
typedef enum
{
SHORT = 0,
LONG = 1
} mytype;
int
fcn (void *array, mytype type, size_t size)
{
void *ptr;
switch (type)
{
case SHORT:
ptr = malloc (size * sizeof(short));

You didn't read the construct you're criticising, did you? You didn't
even read the reason why that construct is better, because here you're
demonstrating exactly why it is better than this code.

Again:

ptr=malloc(num * sizeof *ptr);

is always less likely to break than

ptr=malloc(num * sizeof(type));

If you choose to break that by using void * for everything and then
casting to random types, that's your problem, and it demonstrates
exactly nothing about the need to check anything in well-written C.
It's not my choice, see the reply to Bill Pursell. And of course it's
my problem, I have to use such code, be it well-written C or not.
--
WYCIWYG - what you C is what you get

Feb 9 '07 #120

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
3077
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
2299
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
3706
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
2011
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
4729
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
9583
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
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10039
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...
0
9860
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
7406
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
6668
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
5297
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3955
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
2814
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.