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

R

Raman

Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
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
 
I

Ian Collins

Raman said:
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,"Test1234567890");
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.
 
C

Christopher Layne

Raman said:
char *p=(char *) malloc(100);

char *p = malloc(100 * sizeof *p);

Don't cast the return value from malloc().
strcpy(p,"Test1234567890");
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.
 
C

Christopher Layne

Ian said:
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.
 
I

Ian Collins

Christopher said:
Ian Collins wrote:




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.
 
D

David T. Ashley

Raman said:
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
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.
 
C

CBFalconer

Raman said:
int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
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
 
C

CBFalconer

Ian said:
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
 
R

Ryan Ply

Ian Collins said:
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?

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 -
 
R

Richard Heathfield

Ryan Ply said:
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 said:
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.
 
J

Jens Thoms Toerring

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
 
K

Kenneth Brody

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(int,int);
extern struct foo *AnotherFunction(struct bar *);
#else
extern long SomeFunction();
extern struct foo *AnotherFunction();
#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:[email protected]>
 
R

Richard Tobin

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.
[/QUOTE]
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
 
I

Iwo Mergler

Raman said:
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
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
 
F

Flash Gordon

Richard Tobin wrote, On 01/02/07 17:06:
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.[/QUOTE]

The the system's stdlib.h does not declare malloc then it is not C89
compliant and hence is covered by that Jens stated.
 
C

Charlton Wilbur

CBF> Are there any reliable estimates as to the number of wood
CBF> stove fires annually kindled by BullSchildt books? I have
CBF> the impression the value has been dropping for several years.
CBF> This may be correlated with the disappearance of Herbs from
CBF> the 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
 
M

Mark McIntyre

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
 
C

CBFalconer

Ryan said:
.... snip casting malloc ...

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.

You were using a C++ compiler. Read the errata for K&R.
 
C

CBFalconer

Kenneth said:
.... snip ...

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.

Very bad. There is a major difference (after expanding the macro)
between:

void foo(i) {
...
return ?;
}
and
char foo(i) {
...
return ?;
}

one or t'other will be a compilation error.
 
R

Richard Tobin

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top