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
Ian Collins <ia******@hotma il.comwrites:
Richard Heathfield wrote:
>Ian Collins said:
[...]
>>>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.
Acceptance tests can find bugs; they can't prove the absence of bugs.
It's at least conceivable that you have some bug caused by a piece of
code that's legal C and legal C++, but with different semantics, and
that your acceptance tests aren't quite thorough enough to find it.
Consistently compiling your driver code as pure C, as I suggested in
another response in this thread, might avoid such bugs.

I'm not saying that this is likely or arguing that your approach is
wrong, just suggesting a possible improvement to your methodology.
(Or there might be a good reason why you can't do what I suggested.)

--
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 #161
Keith Thompson wrote:
Ian Collins <ia******@hotma il.comwrites:
>>Richard Heathfield wrote:
>>>Ian Collins said:

[...]
>>>>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.


Acceptance tests can find bugs; they can't prove the absence of bugs.
Nor do I claim that they do. But I will claim that the code developed
in the host environment is better tested that if it had been developed
purely on the embedded target simple because the testing is much easier
and is therefore more rigorous. Some aspects of driver operation are
extremely difficult to unit test consistently on real hardware,
especially if the hardware is deeply embedded.
It's at least conceivable that you have some bug caused by a piece of
code that's legal C and legal C++, but with different semantics, and
that your acceptance tests aren't quite thorough enough to find it.
Consistently compiling your driver code as pure C, as I suggested in
another response in this thread, might avoid such bugs.
I agree. There is also a real chance that one or other of the compiler
have a bug which can lead to behavioural differences. In my experience,
the benefits gained form this approach outweigh the risks.
I'm not saying that this is likely or arguing that your approach is
wrong, just suggesting a possible improvement to your methodology.
(Or there might be a good reason why you can't do what I suggested.)
See may comments of the use of C++ objects for device registers.

--
Ian Collins.
Feb 9 '07 #162
Keith Thompson wrote:
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.
The problem is the other way round. I want the C code to work directly
with C++ objects (pretend bits of hardware).

--
Ian Collins.
Feb 10 '07 #163
Keith Thompson wrote:
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.
Yes, given that (B) is *exactly* quoted
((Type*) malloc (sizeof (Type))).
And (C) is irrelevant (but it adds to that many potential errors I am
going to step onto, yes?)
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)))
Perhaps I want to do

Foo **array;
*array++ = CALLOC_OBJ(Foo) ;

with CALLOC_OBJ doing calloc(sizeof(F oo), 1) in this case (it's g_new0()
in glib-using code). In any case I don't know why I would want to use
NEW_OBJ(ptr) which modifies ptr just to use The Right (or how people say
"idiomatic in c.l.c") '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.
Of course I can. As well I can avoid using goto, I can have single
return in any function, or (going other direction) I can avoid using
stream methods from stdio.h and use raw open/close/read/write, or...
But why? I have never claimed it's necessary to use casts. I did claim
using casts is nice and most importantly harmless in some situations.
You may not agree with "nice" part but you have to prove yet cast
can harm there.

Keith, please tell, did I claim I can't do without casts? If no,
why do you invent extra macros to demonstrate how I can do that?
I could just use malloc(whatever _is_right_in_c_ l_c). If yes,
please quote that.

People again and again tell why I don't have to use cast or something.
I am refusing to follow the advice and then they tell gods will
punish me, and to prove that they show all kinds of errors possible
elsewhere in other situations. Why?
Feb 10 '07 #164
Ian Collins <ia******@hotma il.comwrites:
Keith Thompson wrote:
>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.
The problem is the other way round. I want the C code to work directly
with C++ objects (pretend bits of hardware).
So, for example, a piece of C code in the driver running on the actual
hardware that says:
*ptr = 42;
will simply write 42 into the specified location -- but since that
location might have some special meaning in the target hardware,
there could be some hardware-specific side effects.

Whereas that same piece of code, compiled as C++, running in the host
emulator, might invoke an overloaded "*" function that emulates the
same side effects.

Is that (an oversimplificat ion of) what's going on, or am I missing
the whole point?

I'm beginning to think that the number of posters who have good
reasons to compile the same code as C and as C++ has increased from 1
to 2.

--
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 10 '07 #165
Keith Thompson wrote:
>
So, for example, a piece of C code in the driver running on the actual
hardware that says:
*ptr = 42;
will simply write 42 into the specified location -- but since that
location might have some special meaning in the target hardware,
there could be some hardware-specific side effects.

Whereas that same piece of code, compiled as C++, running in the host
emulator, might invoke an overloaded "*" function that emulates the
same side effects.

Is that (an oversimplificat ion of) what's going on, or am I missing
the whole point?
Yes, that is what's going on.
I'm beginning to think that the number of posters who have good
reasons to compile the same code as C and as C++ has increased from 1
to 2.
:)

--
Ian Collins.
Feb 10 '07 #166
Yevgen Muntyan <mu************ ****@tamu.eduwr ites:
[...]
>Yevgen Muntyan <mu************ ****@tamu.eduwr ites:
[snip]
>>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.
[snip]
Keith, please tell, did I claim I can't do without casts? If no,
why do you invent extra macros to demonstrate how I can do that?
I could just use malloc(whatever _is_right_in_c_ l_c). If yes,
please quote that.
You didn't say in so many words that you "can't do without casts", but
you did say, in so many words, that you "need" casts. In fact, you
don't *need* to use casts.
People again and again tell why I don't have to use cast or something.
I am refusing to follow the advice and then they tell gods will
punish me, and to prove that they show all kinds of errors possible
elsewhere in other situations. Why?
I've never claimed the gods will punish you, so I can't answer that.
I do question your claim that adding a cast can make for a "safer
expression". The expression (the result of malloc()) has a type,
namely void*. (Admittedly void* is in some sense a weaker type than,
say, foo*.) It acquires another type whether you use a cast or not.

But I'm already tired of this thread, even though I've hardly posted
to it, so I don't plan to debate the point any further.

--
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 10 '07 #167
Keith Thompson wrote:
Yevgen Muntyan <mu************ ****@tamu.eduwr ites:
[...]
>>Yevgen Muntyan <mu************ ****@tamu.eduwr ites:

[snip]
>>>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.

[snip]
>Keith, please tell, did I claim I can't do without casts? If no,
why do you invent extra macros to demonstrate how I can do that?
I could just use malloc(whatever _is_right_in_c_ l_c). If yes,
please quote that.

You didn't say in so many words that you "can't do without casts", but
you did say, in so many words, that you "need" casts. In fact, you
don't *need* to use casts.
*I* do need them because they help *me* avoid stupid bugs.
I might have misused the English word "need", I do not feel
exact sense it carries when I say "I need". I guess "I want"
is better here, but if I used it, it would be immediately
interpreted as I want that cast in the same way as I want
ice cream, without any rational base.
>People again and again tell why I don't have to use cast or something.
I am refusing to follow the advice and then they tell gods will
punish me, and to prove that they show all kinds of errors possible
elsewhere in other situations. Why?

I've never claimed the gods will punish you, so I can't answer that.
You didn't. You just added to the pool of all those errors I
should expect in my code by providing your example (C), even
though that's a type of error which is *impossible* if I use
the macro instead of blind casts here and there (the casts
which I don't use).
I do question your claim that adding a cast can make for a "safer
expression". The expression (the result of malloc()) has a type,
namely void*. (Admittedly void* is in some sense a weaker type than,
say, foo*.) It acquires another type whether you use a cast or not.
Yes, and malloc() is also not blind since it doesn't have eyes.
If you didn't understand what I meant by "typeless", I apologize
for poor wording. I doubt it though.
But I'm already tired of this thread, even though I've hardly posted
to it, so I don't plan to debate the point any further.
You hardly posted, but you did add to collective wisdom's "Wrong.",
didn't you.
Feb 10 '07 #168
Keith Thompson said:
Ian Collins <ia******@hotma il.comwrites:
>Richard Heathfield wrote:
>>Ian Collins said:
[...]
>>>>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.

Acceptance tests can find bugs; they can't prove the absence of bugs.
Whilst I agree with your general line of argument, Keith, I think it
bears mentioning that acceptance tests are generally not intended even
to find bugs (let alone prove their absence, which they can't do anyway
as you rightly say), but rather to determine whether the software as a
whole performs substantially according to its specification: not "is
this program bug-free as far as we can tell?" but "is this program good
enough for our requirements?"

Personally, I'm of the opinion that any bug is one bug too many, but
many people seem to think that they'd rather use the software some time
this side of eternity and are therefore quite happy to put up with the
odd bug.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 10 '07 #169
Richard Heathfield <rj*@see.sig.in validwrites:
Keith Thompson said:
>Ian Collins <ia******@hotma il.comwrites:
>>Richard Heathfield wrote:
Ian Collins said:
[...]
>>>>>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.

Acceptance tests can find bugs; they can't prove the absence of bugs.

Whilst I agree with your general line of argument, Keith, I think it
bears mentioning that acceptance tests are generally not intended even
to find bugs (let alone prove their absence, which they can't do anyway
as you rightly say), but rather to determine whether the software as a
whole performs substantially according to its specification: not "is
this program bug-free as far as we can tell?" but "is this program good
enough for our requirements?"
It reduces to the same thing if you define "bug" as "failure to meet
requirements". The trick then is to write bug-free requirements.
Regress until dizzy.
Personally, I'm of the opinion that any bug is one bug too many, but
many people seem to think that they'd rather use the software some time
this side of eternity and are therefore quite happy to put up with the
odd bug.
Well, not happy, but tolerant. Good point, though.

--
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 10 '07 #170

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
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
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...
1
9990
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
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...
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...
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.