473,769 Members | 5,757 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
Richard Heathfield wrote:
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.
I'm not sure if you are being deliberately obtuse.

My point is there is sometimes value in having C code which is valid
C++. The driver code in question is compiled as C for the embedded
target, but compiled with the host C++ compiler for testing in a
hardware simulator.

So the code in question is written in the subset of C that is valid C++.

--
Ian Collins.
Feb 9 '07 #151
Ian Collins said:
Richard Heathfield wrote:
>Ian Collins said:
>>>Richard Heathfield wrote:

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.
I'm not sure if you are being deliberately obtuse.
No, I'm usually pretty acute.
My point is there is sometimes value in having C code which is valid
C++. The driver code in question is compiled as C for the embedded
target, but compiled with the host C++ compiler for testing in a
hardware simulator.
Not wise, in my opinion. Your test environment does not adequately
reflect your production environment. You wouldn't try to pull that
stunt with Perl on the target and COBOL on the simulator, would you? So
why do it with C and C++?
So the code in question is written in the subset of C that is valid
C++.
With identical semantics? Are you *sure*? And once you've answered in
the affirmative, ask yourself whether you are *really* sure.

--
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 #152
Richard Heathfield wrote:
Ian Collins said:
>>Richard Heathfield wrote:
>>>
Fine, in which case it isn't C++, so you don't need the cast on
malloc.

I'm not sure if you are being deliberately obtuse.

No, I'm usually pretty acute.
I had noticed...
>>My point is there is sometimes value in having C code which is valid
C++. The driver code in question is compiled as C for the embedded
target, but compiled with the host C++ compiler for testing in a
hardware simulator.

Not wise, in my opinion. Your test environment does not adequately
reflect your production environment.
The value gained form being able to test drivers or a complete embedded
system off the target. We built up a very accurate simulation of the
micro we were using which enabled us to fully test our software before
we had hardware.
>
You wouldn't try to pull that
stunt with Perl on the target and COBOL on the simulator, would you? So
why do it with C and C++?
Is there a common subset of Perl and COBOL?
>
>>So the code in question is written in the subset of C that is valid
C++.

With identical semantics? Are you *sure*? And once you've answered in
the affirmative, ask yourself whether you are *really* sure.
Yes, and we back that up with acceptance tests that run against the
simulation and the final product.

--
Ian Collins.
Feb 9 '07 #153
Ian Collins wrote:
I'm not sure if you are being deliberately obtuse.

My point is there is sometimes value in having C code which is valid
C++. The driver code in question is compiled as C for the embedded
target, but compiled with the host C++ compiler for testing in a
hardware simulator.

So the code in question is written in the subset of C that is valid C++.
Why not just compile them both under C mode?
Feb 9 '07 #154
Christopher Layne wrote:
Ian Collins wrote:

>>I'm not sure if you are being deliberately obtuse.

My point is there is sometimes value in having C code which is valid
C++. The driver code in question is compiled as C for the embedded
target, but compiled with the host C++ compiler for testing in a
hardware simulator.

So the code in question is written in the subset of C that is valid C++.


Why not just compile them both under C mode?
The simulation uses C++ for things like hardware registers. In C mode,
a register is a typedef for the appropriate unsigned integer type. In
C++ mode, it can be a class object with conversion and assignment
operators that trigger state changes in the simulation when the register
is written or read.

--
Ian Collins.
Feb 9 '07 #155
"Ian Collins" <ia******@hotma il.comwrote in message
news:53******** ******@mid.indi vidual.net...
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++. 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.
But you're _not_ testing your C drivers, you're testing
similar-but-not-identical C++ drivers.

Even if your code uses the common subset syntax-wise, you may
accidentally use constructs that mean different (but equally valid)
things in the two languages, e.g. const, or run into compiler
optimization differences.

C++ provides a simple and convenient mechanism for mixing in C objects.
Why not use it and avoid the potential pitfalls?

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Feb 9 '07 #156
Yevgen Muntyan <mu************ ****@tamu.eduwr ites:
Christopher Layne wrote:
>Yevgen Muntyan wrote:
>>>>#define FOO_NEW() ((Foo*) malloc (sizeof (Foo))) // *must* cast here
No. It's not. It's not clear, it's obtuse and pointless monkeying that
*reduces* visible intent.
What do you do if you need to replace malloc() with another allocator?
Grep? While this macro is indeed stupid, it was an example of where
cast is needed.
*If* you write a macro which allocates a Foo structure (this macro can
do arbitrary nice or complex things, and there *are* macros like that
in real code) you better make it of type Foo*.

Yevgen
What are you NOT getting about the fact that the cast is not needed
in ISO C?
Do you know the purpose and characteristics of void pointers?

You're not kidding, are you? I said *I need* cast because I want a safer
expression. If I apply cast, the expression acquires a type.

((Type*) malloc (sizeof (Type)))
Ok, I can *sort of* see your point here. Without the cast, the
expression is of type void*, which will be implicitly converted to any
pointer-to-object type. It's less safe in the sense that if you apply
sizeof to the wrong thing, the compiler won't warn you about it:

(A):
double *p1;
int *p2;
p1 = malloc(sizeof *p2);

Whereas if you use the type, then getting the type wrong will give you
a constraint error and a required diagnostic:

(B):
double *p1;
int *p2;
p1 = (int*)malloc(si zeof(int)); /* Compiler catches error */

But if you have the correct type in the cast, but the wrong type in
the sizeof argument, you're back to another error that the compiler
won't catch:

(C):
double *p1;
int *p2;
p1 = (double*)malloc (sizeof(int));

What you're doing is basically case (B) with the two occurrences of
the type name kept in synch by using a macro.

But if you want to use a macro, why not apply the same technique to
case (A), giving you just as much safety?

(D):
#define NEW_OBJ(ptr) ((ptr) = malloc(sizeof *(ptr)))
#define NEW_ARR(ptr, count) ((ptr) = malloc(count * sizeof *(ptr)))

double *p1;
int *p2;
NEW_OBJ(p1);
if (p1 == NULL) {
/* allocation failed */
}
NEW_ARR(p2, 10);
if (p2 == NULL) {
/* allocation failed */
}

Personally, I'm content to keep the sizeof argument consistent
manually, but you can use macros to do this for you *without* using
unnecessary casts.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 9 '07 #157
Stephen Sprunk wrote:
"Ian Collins" <ia******@hotma il.comwrote in message
news:53******** ******@mid.indi vidual.net...
>>
It's not pointless if you are using C++ for hardware simulations to test
your C drivers.

But you're _not_ testing your C drivers, you're testing
similar-but-not-identical C++ drivers.
You could argue the same for any off-target testing. The generated code
is different. The logic remains the same.
Even if your code uses the common subset syntax-wise, you may
accidentally use constructs that mean different (but equally valid)
things in the two languages, e.g. const, or run into compiler
optimization differences.
I've been using this technique for fifteen years or so, using the same
evolving set of tools, so I know the differences between the two and how
to avoid them. I've even checked the assembler output for various bits
of code compiled with the C and C++ compilers.

The advantages of developing and debugging the drivers on a host rather
then a target environment (less these days than a decade ago) still
outweighs any risks. As I said elsethread, I always use automated
acceptance tests that run on both the target and the simulation. Host
based simulations aren't a replacement for target testing, but they can
be a replacement for target debugging.
C++ provides a simple and convenient mechanism for mixing in C objects.
Why not use it and avoid the potential pitfalls?
The code under test is C and I abhor conditional compilation for testing
in source files.

--
Ian Collins.
Feb 9 '07 #158
"Yevgen Muntyan" <mu************ ****@tamu.eduwr ote in message
news:eq******** **@news.tamu.ed u...
Indeed, code tends to break when you don't touch it. You
put cast in, it explodes in two months.
Bit rot is a very real phenomenon, though Murphy's Law states that your
code won't explode until you're doing a demo for an important customer.
What you're all saying is why it's not a good idea to
use cast. And that's indeed true, it's not a good idea
to cast when you don't have to. What's not true
is that any given piece of code with cast is wrong and
dangerous in any situation.
It's not guaranteed to be wrong. However, casting hides the cases where
it _is_ wrong, and not casting exposes that. Coding so that you expose
bugs, not hide them, is good practice.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking
--
Posted via a free Usenet account from http://www.teranews.com

Feb 9 '07 #159
Ian Collins <ia******@hotma il.comwrites:
[...]
My point is there is sometimes value in having C code which is valid
C++. The driver code in question is compiled as C for the embedded
target, but compiled with the host C++ compiler for testing in a
hardware simulator.

So the code in question is written in the subset of C that is valid C++.
Interesting.

You need your drivers to be callable from C++ on the host system, so
you write them to be compilable as either C or C++, restricting
yourself to the intersection of the two languages. It seems to me
your requirement is perfectly reasonable, but I'm not convinced you've
found the best solution. Have you considered instead compiling your
drivers as C on the host system, and calling them from C++ using C++'s
'extern "C"' feature? Your headers would still have to be valid as
both C and C++ (possibly using "#ifdef __cplusplus" here and there),
but the actual implementation of the drivers could be pure C.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 9 '07 #160

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
9423
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
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...
0
8869
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
5445
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
2
3560
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.