473,395 Members | 1,941 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Arraym malloc() and free() question

Hello,
I have a question regarding malloc and free.
Here my code sample:

int main()
{
/* allocating dynamic memory for array */
int* array = (int*) malloc(5 * sizeof(int));

/* ... program code ... */

array = (int*) malloc(4 * sieof(int));

free(array);
}

Now my question: The second time I allocate
memory for array, what happens to the
address that I got with the first malloc?
Is it freed automatically?

Martin
Nov 14 '05 #1
36 2221
ma***********@gmx.de (Martin Andert) writes:
int main()
{
/* allocating dynamic memory for array */
int* array = (int*) malloc(5 * sizeof(int));
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.

* If you cast to the wrong type by accident, odd failures can
result.

Some others do disagree, such as P.J. Plauger (see article
<9s*****************@nwrddc01.gnilink.net>).

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *x = malloc (128 * sizeof (int)); /* Don't do this! */

Instead, write it this way:

int *x = malloc (128 * sizeof *x);

There's a few reasons to do it this way:

* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.

This is more of a problem in a large program, but it's still
convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.
/* ... program code ... */

array = (int*) malloc(4 * sieof(int));

free(array);
}

Now my question: The second time I allocate
memory for array, what happens to the
address that I got with the first malloc?
Is it freed automatically?


No. If you didn't save a copy of the original pointer, the
memory is wasted ("leaked").
--
"A lesson for us all: Even in trivia there are traps."
--Eric Sosman
Nov 14 '05 #2
>I have a question regarding malloc and free.
Here my code sample:

int main()
{
/* allocating dynamic memory for array */
int* array = (int*) malloc(5 * sizeof(int));

/* ... program code ... */

array = (int*) malloc(4 * sieof(int));

free(array);
}

Now my question: The second time I allocate
memory for array, what happens to the
address that I got with the first malloc?
You have a memory leak (assuming you didn't save the address
elsewhere). This is a BAD THING (tm).

A memory leak should not cause crashing in a properly written program
(CHECK if malloc() returns NULL before using the result!) but it
may cause malloc() to fail, especially if the leak is in a loop.
Is it freed automatically?


Memory allocated with malloc() is not freed automatically, except
perhaps when the program calls exit().

Gordon L. Burditt
Nov 14 '05 #3
Ben Pfaff wrote:
cat main.c int main(int argc, char* argv[]) {
// allocating dynamic memory for array
int* array = (int*)malloc(5*sizeof(int));

// ... program code ...

array = (int*)malloc(4*sizeof(int));// error: memory leak!

free(array);
return 0;
}
gcc -Wall -std=c99 -pedantic -o main main.c main.c: In function `main':
main.c:3: warning: implicit declaration of function `malloc'
main.c:9: warning: implicit declaration of function `free'
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to
#include <stdlib.h>, which leads to undefined behavior.


Nonsense!
Only inferior compiler fail to warn about
implicit declaration of function `malloc'
Nov 14 '05 #4
Martin Andert wrote, without checking the FAQ or following the newsgroup
before posting:
Hello,
I have a question regarding malloc and free.
Here my code sample:
You need to
#include <stdlib.h>
No doubt the reason for the silly casts on the return value from malloc
was to make the compiler shut up. Leaving out this header (or the
equivalent declarations and definitions found there) means your C89
compiler assumes incorrectly that malloc returns an int. When you get a
C99 compiler, it will barf instead, since implicit int is gone.
int main()
{
/* allocating dynamic memory for array */
int* array = (int*) malloc(5 * sizeof(int));
I think you mean
int *array = malloc(5 * sizeof *array);
That magic number (5) is poor practice, and you should check the return
value of malloc. Of course, people following expected usenet behavior
would know that, because they would have checked the FAQ and followed
the newsgroup.
/* ... program code ... */

array = (int*) malloc(4 * sieof(int)); See the comments above. In addition, you need to either free array
before this malloc call or use realloc instead.
free(array);
}

Now my question: The second time I allocate
memory for array, what happens to the
address that I got with the first malloc? You lost it. You have a memory leak.
Is it freed automatically?
No.
Martin


People named 'Martin' should know to check the FAQ and follow the
newsgroup before posting.

Martin
Nov 14 '05 #5
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Ben Pfaff wrote:

[...]
I don't recommend casting the return value of malloc():
* The cast is not required in ANSI C.
* Casting its return value can mask a failure to
#include <stdlib.h>, which leads to undefined behavior.


Nonsense!
Only inferior compiler fail to warn about
implicit declaration of function `malloc'


Perhaps, but there's no reason to depend on your compiler to issue
this (common but not universal) warning.

With the cast, if you forget to #include <stdlib.h>, you'll *probably*
get a warning about the call to malloc() with no visible prototype.
(gcc 3.3.3 doesn't give this warning by default; it does if you
specify "-Wall". Yes, you should always use "-Wall", but not everyone
does.)

Without the cast, if you forget to #include <stdlib.h>, you'll *almost
certainly* get an additional diagnostic about an implicit conversion
from type "int".

And of course if you properly #include <stdlib.h> *and* leave out the
cast, everything will work just fine.

The cast is completely unnecessary unless, for some reason, you
actually need to write code that's compatible with both C and C++
(C++, unlike C, has no implicit conversion from void* to other pointer
types). Very few people have such a need. <OT>Pure C++ code should
use new rather than malloc().</OT>

ERT attempts to refute Ben's second point, that the cast can mask a
failure to #include <stdlib.h>. But his first point, that the cast is
not required, is much stronger. Why use a cast when it's not needed?

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #6
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
[snip]
With the cast, if you forget to #include <stdlib.h>, you'll *probably*
get a warning about the call to malloc() with no visible prototype. [snip] Without the cast, if you forget to #include <stdlib.h>, you'll *almost
certainly* get an additional diagnostic about an implicit conversion
from type "int".


Only "almost certainly"? Isn't assignment of an int to a pointer a
constraint violation, which therefore requires a diganostic?

Alex
Nov 14 '05 #7
In <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Ben Pfaff wrote:[...]
I don't recommend casting the return value of malloc():
* The cast is not required in ANSI C.
* Casting its return value can mask a failure to
#include <stdlib.h>, which leads to undefined behavior.


Nonsense!
Only inferior compiler fail to warn about
implicit declaration of function `malloc'


Perhaps, but there's no reason to depend on your compiler to issue
this (common but not universal) warning.

With the cast, if you forget to #include <stdlib.h>, you'll *probably*
get a warning about the call to malloc() with no visible prototype.
(gcc 3.3.3 doesn't give this warning by default; it does if you
specify "-Wall". Yes, you should always use "-Wall", but not everyone
does.)

Without the cast, if you forget to #include <stdlib.h>, you'll *almost
certainly* get an additional diagnostic about an implicit conversion
from type "int".


Although I know what you mean by "almost certainly", it's better to
explicitly point out that a compiler diagnostic is required by the C
standard in this case.
ERT attempts to refute Ben's second point, that the cast can mask a
failure to #include <stdlib.h>. But his first point, that the cast is
not required, is much stronger. Why use a cast when it's not needed?


The most reasonable answer was provided by P.J. Plauger: because the
paying customer wants to compile your code with a C++ compiler. Of
course, this doesn't justify the cast in other situations, not even when
the code needs to be used in a C++ program: it can be separately compiled
with a C compiler and linked with the other object files of the program.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #8
In <2v*************@uni-berlin.de> "Alex Fraser" <me@privacy.net> writes:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
[snip]
With the cast, if you forget to #include <stdlib.h>, you'll *probably*
get a warning about the call to malloc() with no visible prototype.

[snip]
Without the cast, if you forget to #include <stdlib.h>, you'll *almost
certainly* get an additional diagnostic about an implicit conversion
from type "int".


Only "almost certainly"? Isn't assignment of an int to a pointer a
constraint violation, which therefore requires a diganostic?


It does, but the diagnostic need not be about ``an implicit conversion
from type "int"''. The diagnostic could say "your code stinks" as far as
the standard is concerned and it could also be issued for translation
units that don't require any diagnostic, thus carrying zilch useful
information.

Getting a diagnostic about ``an implicit conversion from type "int"'' is
a quality of implementation issue, hence the "almost certainly" used by
Keith.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #9
In article <cm**********@sunnews.cern.ch>, Dan Pop <Da*****@cern.ch> wrote:
ERT attempts to refute Ben's second point, that the cast can mask a
failure to #include <stdlib.h>. But his first point, that the cast is
not required, is much stronger. Why use a cast when it's not needed?
The most reasonable answer was provided by P.J. Plauger: because the
paying customer wants to compile your code with a C++ compiler.


Are there really C++ compilers that don't have a C mode for compiling
C files? If so, why do paying customers buy them?

-- Richard
Nov 14 '05 #10
On Wed, 10 Nov 2004 15:30:46 -0000, in comp.lang.c , "Alex Fraser"
<me@privacy.net> wrote:
Only "almost certainly"? Isn't assignment of an int to a pointer a
constraint violation, which therefore requires a diganostic?


Perhaps, but AFAIR a compiler is only obligated to issue at least one
diagnostic. Code like this

int main(void)
int x = (long)12;
double *x = malloc(12);
}

might never get a diagnostic about the malloc call, having already issued
at least one.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #11
"Alex Fraser" <me@privacy.net> writes:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
[snip]
With the cast, if you forget to #include <stdlib.h>, you'll *probably*
get a warning about the call to malloc() with no visible prototype.

[snip]
Without the cast, if you forget to #include <stdlib.h>, you'll *almost
certainly* get an additional diagnostic about an implicit conversion
from type "int".


Only "almost certainly"? Isn't assignment of an int to a pointer a
constraint violation, which therefore requires a diganostic?


You're right, it is. The "almost" was intended either to cover either
ancient non-conforming compilers or my own laziness in failing to take
the time to convince myself that a diagnostic is mandatory.

(Dan's comment that I was considering that the diagnostic doesn't have
to be meaningful is a good explanation, but I confess that it's not
what I had in mind.)

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #12
On Wed, 10 Nov 2004 06:44:45 UTC, ma***********@gmx.de (Martin Andert)
wrote:
Hello,
I have a question regarding malloc and free.
Here my code sample:

int main() int main(void) {
/* allocating dynamic memory for array */
int* array = (int*) malloc(5 * sizeof(int));
casting the result of an function returning a pointer to void invokes
undefined behavior as it hides the possible error that there is no
prototype of the function known to the compiler.
/* ... program code ... */

array = (int*) malloc(4 * sieof(int));
same as above.

this produces clearly a memory leak as the reference to the memoty
block allocated prior gets lost.
free(array);
}

Now my question: The second time I allocate
memory for array, what happens to the
address that I got with the first malloc?
It gets still lost - but the block itself lefts allocated, producing a
memory leak.
Is it freed automatically?


No.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #13
On Wed, 10 Nov 2004 07:19:44 UTC, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> wrote:
Ben Pfaff wrote:
> cat main.c

int main(int argc, char* argv[]) {
// allocating dynamic memory for array
int* array = (int*)malloc(5*sizeof(int));

// ... program code ...

array = (int*)malloc(4*sizeof(int));// error: memory leak!

free(array);
return 0;
}
> gcc -Wall -std=c99 -pedantic -o main main.c

main.c: In function `main':
main.c:3: warning: implicit declaration of function `malloc'
main.c:9: warning: implicit declaration of function `free'
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to
#include <stdlib.h>, which leads to undefined behavior.


Nonsense!
Only inferior compiler fail to warn about
implicit declaration of function `malloc'


Rubbish, there is nothing in the standard that requires an diagnostic
about that. The standard say only that an fuction that gets called
without prototype will return int. And int is somewhat different from
a pointer to any type that undefined behavior occures.

It is voluntary service to its customer when a compiler gives in one
of its options an ddiagnostic of 'missing prototype'. There is nothing
that can require that. Even gcc will NOT give that diagnostic - it may
give any diagnistic it likes - or even none. Casting from something to
something else is clearly the requirement to the compiler: "be quite -
I know what I do". But in that case you are lying to it as you clearly
NOT knows what you does. Kowing what you does would mean NEVER casting
a pointer to void to something else (what even ever) to avoid going
into the lands of undefined behavior.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #14
On Wed, 10 Nov 2004 15:30:46 UTC, "Alex Fraser" <me@privacy.net>
wrote:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
[snip]
With the cast, if you forget to #include <stdlib.h>, you'll *probably*
get a warning about the call to malloc() with no visible prototype.

[snip]
Without the cast, if you forget to #include <stdlib.h>, you'll *almost
certainly* get an additional diagnostic about an implicit conversion
from type "int".


Only "almost certainly"? Isn't assignment of an int to a pointer a
constraint violation, which therefore requires a diganostic?


An diagnostic is required, right. But there is nothing that requires
THIS text. It is on the compiler to cry instead "you are starting the
3. world wide war now" or "you are an idiot" or "please learn C before
you use this language". It may break the translation on that stage or
produce a binary
when the sun shines and none when it is april, it may give you any
time another text in the diagnostic anyway.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #15
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Wed, 10 Nov 2004 06:44:45 UTC, ma***********@gmx.de (Martin Andert)
wrote:
Hello,
I have a question regarding malloc and free.
Here my code sample:

int main()

int main(void)
{
/* allocating dynamic memory for array */
int* array = (int*) malloc(5 * sizeof(int));


casting the result of an function returning a pointer to void invokes
undefined behavior as it hides the possible error that there is no
prototype of the function known to the compiler.


No, it doesn't invoke undefined behavior. Assuming a proper
"#include <stdlib.h>" (which the original program lacked), the
cast is merely useless.

It does invoke undefined behavior from the readers of comp.lang.c, but
that's outside the scope of the standard.

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #16
In <wm***************************@URANUS1.DV-ROSENAU.DE> "Herbert Rosenau" <os****@pc-rosenau.de> writes:
about that. The standard say only that an fuction that gets called
without prototype will return int.


Nope, it doesn't. It returns whatever type was specified in its
declaration (which needs not be a prototype declaration). A function
called without a *declaration* in scope is implicitly declared as
returning int.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #17
On Thu, 11 Nov 2004 12:48:06 UTC, Keith Thompson <ks***@mib.org>
wrote:
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Wed, 10 Nov 2004 06:44:45 UTC, ma***********@gmx.de (Martin Andert)
wrote:
Hello,
I have a question regarding malloc and free.
Here my code sample:

int main() int main(void)
{
/* allocating dynamic memory for array */
int* array = (int*) malloc(5 * sizeof(int));


casting the result of an function returning a pointer to void invokes
undefined behavior as it hides the possible error that there is no
prototype of the function known to the compiler.


No, it doesn't invoke undefined behavior. Assuming a proper
"#include <stdlib.h>" (which the original program lacked), the
cast is merely useless.


It IS undefined behavior to convert an by malloc not used int variable
to a pointer. Ther is nothing that says that a function returnin void*
must set up the place the caller thinks a function returning int uses
as result. There is nothing that defines that a voud* has the same
size, alignment... as an int - so undefined behavior is invoked. Read
the standard!

The only case using a function that returns something unequal to int
is to use prototypes or other ways that lets the compiler _know_, not
assume the type of the value a function returns. Anything else IS
invoking undefined behavior. Clearly casting something the compiler
assumes instead of knowing is invokung the lands of undefined behavior
too.

It does invoke undefined behavior from the readers of comp.lang.c, but
that's outside the scope of the standard.

Rubbish. It is invoking undefining behavior in any case. Read the
standard.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #18
On Thu, 11 Nov 2004 14:20:14 UTC, Da*****@cern.ch (Dan Pop) wrote:
In <wm***************************@URANUS1.DV-ROSENAU.DE> "Herbert Rosenau" <os****@pc-rosenau.de> writes:
about that. The standard say only that an fuction that gets called
without prototype will return int.


Nope, it doesn't. It returns whatever type was specified in its
declaration (which needs not be a prototype declaration). A function
called without a *declaration* in scope is implicitly declared as
returning int.

Dan


From sight of the caller an unspecified function returns int - even as
the declaration that is outside the sight of the compiler at calling
point does something else. So the compiler uses the int it assumes the
calle had returned = undefined behavor.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #19
On Thu, 11 Nov 2004 18:02:13 +0000, Herbert Rosenau wrote:
On Thu, 11 Nov 2004 14:20:14 UTC, Da*****@cern.ch (Dan Pop) wrote:
In <wm***************************@URANUS1.DV-ROSENAU.DE> "Herbert
Rosenau" <os****@pc-rosenau.de> writes:
>about that. The standard say only that an fuction that gets called
>without prototype will return int.


Nope, it doesn't. It returns whatever type was specified in its
declaration (which needs not be a prototype declaration). A function
called without a *declaration* in scope is implicitly declared as
returning int.
Except in C99.
Dan


From sight of the caller an unspecified function returns int - even as
the declaration that is outside the sight of the compiler at calling
point does something else.


Which is what Dan said. It is different to what you said above because of
the distinction between the terms "declaration" and "prototype": you can
have a declaration in scope without having a prototype in scope. Prototypes
are the "new" function declaration and definition syntax that originated in
C++ and was introduced into C by the first, C89 standard.

long foo(); /* This is a declaration but not a prototype */
long foo(void); /* This is a declaration and a prototype */

long bar(x) long x; { return x; } /* This is a definition but not a prototype */
long bar(long x) { return x; } /* This is a definition and a prototype */

Definitions serve as declarations too.
Nov 14 '05 #20

In article <ln************@nuthaus.mib.org>, Keith Thompson <ks***@mib.org> writes:
"Alex Fraser" <me@privacy.net> writes:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...

Without the cast, if you forget to #include <stdlib.h>, you'll *almost
certainly* get an additional diagnostic about an implicit conversion
from type "int".


Only "almost certainly"? Isn't assignment of an int to a pointer a
constraint violation, which therefore requires a diganostic?


You're right, it is. The "almost" was intended either to cover either
ancient non-conforming compilers or my own laziness in failing to take
the time to convince myself that a diagnostic is mandatory.


There's also the case where stdlib.h is not included but the code
supplies its own prototype for malloc. No constraint is violated
(by the use of malloc without a cast), so the implementation need
not issue a diagnostic, but the code still invokes undefined
behavior.

This says nothing about why casting the return value of malloc is
a bad idea, of course. It's just another justification for that
"almost".

--
Michael Wojcik mi************@microfocus.com

Duck: No secret what's worth a hoot ought to be kept quiet.
Pogo: Secrets is usually perty doggone fascinatin'.
Duck: Egg-zackly ... it's completely illogical to keep a secret secret.
Pogo: An' unfair. -- Walt Kelly
Nov 14 '05 #21
In article <cn*********@news4.newsguy.com>,
Michael Wojcik <mw*****@newsguy.com> wrote:
There's also the case where stdlib.h is not included but the code
supplies its own prototype for malloc. No constraint is violated
(by the use of malloc without a cast), so the implementation need
not issue a diagnostic, but the code still invokes undefined
behavior.


If you've given your own prototype for malloc, yes, because you Really
Do Need size_t for it. (Unless you've included <stddef.h> instead of
<stdlib.h>.) But you're invoking undefined behavior by giving it the
wrong argument type, not by using the wrong return type.

If you've given a declaration with a correct return type and call it
with an argument of the correct type, like this:
--------
void *malloc();
int *malloc_an_int()
{
return malloc(sizeof int);
}
--------
then you're not invoking undefined behavior, only bad form.

If you've given a declaration with an incorrect return type:
--------
malloc(); /*implicit int - incorrect*/
/*-OR-*/
int malloc(); /*explicit incorrect return type*/
--------
then assigning the return value without a cast is still a constraint
violation.
dave

--
Dave Vandervies dj******@csclub.uwaterloo.ca
although come to think of it if you didn't enjoy sounding stupid you wouldn't
be talking about things you don't understand. never mind...
--David C. Ullrich roasts a troll in comp.lang.c++
Nov 14 '05 #22
Dave Vandervies wrote:

If you've given a declaration with a correct return type and call it
with an argument of the correct type, like this:
--------
void *malloc();
int *malloc_an_int()
{
return malloc(sizeof int);
}
--------
then you're not invoking undefined behavior, only bad form.


It's implementation-specified whether this invokes
undefined behavior. `size_t' might be a type that is
subject to argument promotions in the absence of a
prototype, and then you'd be calling malloc() with the
promoted type rather than the expected type.

Let's summarize all this blather about calling
undeclared functions with one piece of advice: Don't.
See the commentary on the Fourth Commandment at

http://www.lysator.liu.se/c/ten-commandments.html

--
Er*********@sun.com

Nov 14 '05 #23
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Thu, 11 Nov 2004 12:48:06 UTC, Keith Thompson <ks***@mib.org>
wrote:
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
> On Wed, 10 Nov 2004 06:44:45 UTC, ma***********@gmx.de (Martin Andert)
> wrote:
>
>> Hello,
>> I have a question regarding malloc and free.
>> Here my code sample:
>>
>> int main()
> int main(void)
>> {
>> /* allocating dynamic memory for array */
>> int* array = (int*) malloc(5 * sizeof(int));
>
> casting the result of an function returning a pointer to void invokes
> undefined behavior as it hides the possible error that there is no
> prototype of the function known to the compiler.


No, it doesn't invoke undefined behavior. Assuming a proper
"#include <stdlib.h>" (which the original program lacked), the
cast is merely useless.


It IS undefined behavior to convert an by malloc not used int variable
to a pointer. Ther is nothing that says that a function returnin void*
must set up the place the caller thinks a function returning int uses
as result. There is nothing that defines that a voud* has the same
size, alignment... as an int - so undefined behavior is invoked. Read
the standard!


I didn't say anything about a function returning int.

The original program does invoke undefined behavior, because there's
no declaration for malloc (because there's no #include <stdlib.h>).
But that's not what you said. You said that "casting the result of an
function returning a pointer to void invokes undefined behavior".

Taken literally, your statement implies that the following:

#include <stdlib.h>
int main()
{
int *ptr;
ptr = (int*)malloc(sizeof(int));
return 0;
}

invokes undefined behavior. It doesn't.

I'm sure that wasn't what you meant, but I was responding to what you
actually wrote.

--
Keith Thompson (The_Other_Keith) 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.
Nov 14 '05 #24
In <cn*********@news4.newsguy.com> mw*****@newsguy.com (Michael Wojcik) writes:

In article <ln************@nuthaus.mib.org>, Keith Thompson <ks***@mib.org> writes:
"Alex Fraser" <me@privacy.net> writes:
> "Keith Thompson" <ks***@mib.org> wrote in message
> news:ln************@nuthaus.mib.org...
>>
>> Without the cast, if you forget to #include <stdlib.h>, you'll *almost
>> certainly* get an additional diagnostic about an implicit conversion
>> from type "int".
>
> Only "almost certainly"? Isn't assignment of an int to a pointer a
> constraint violation, which therefore requires a diganostic?


You're right, it is. The "almost" was intended either to cover either
ancient non-conforming compilers or my own laziness in failing to take
the time to convince myself that a diagnostic is mandatory.


There's also the case where stdlib.h is not included but the code
supplies its own prototype for malloc. No constraint is violated
(by the use of malloc without a cast), so the implementation need
not issue a diagnostic, but the code still invokes undefined
behavior.


I can't see any undefined behaviour if the code supplies the correct
prototype for malloc. Which is perfectly possible, because there are
several other headers defining size_t.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #25
In <pa****************************@netactive.co.uk> Lawrence Kirby <lk****@netactive.co.uk> writes:
On Thu, 11 Nov 2004 18:02:13 +0000, Herbert Rosenau wrote:
On Thu, 11 Nov 2004 14:20:14 UTC, Da*****@cern.ch (Dan Pop) wrote:
In <wm***************************@URANUS1.DV-ROSENAU.DE> "Herbert
Rosenau" <os****@pc-rosenau.de> writes:

>about that. The standard say only that an fuction that gets called
>without prototype will return int.

Nope, it doesn't. It returns whatever type was specified in its
declaration (which needs not be a prototype declaration). A function
called without a *declaration* in scope is implicitly declared as
returning int.


Except in C99.


In C99 this whole discussion is pointless: calling malloc without a
declaration in scope no longer invokes undefined behaviour, a diagnostic
is required.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #26
In <cn**********@news1brm.Central.Sun.COM> Eric Sosman <er*********@sun.com> writes:
Dave Vandervies wrote:

If you've given a declaration with a correct return type and call it
with an argument of the correct type, like this:
--------
void *malloc();
int *malloc_an_int()
{
return malloc(sizeof int);
}
--------
then you're not invoking undefined behavior, only bad form.
It's implementation-specified whether this invokes


Nope, it is implementation-specific but not implementation-specified.
There is nothing in the C standard requiring an implementation to specify
how size_t is defined.
undefined behavior. `size_t' might be a type that is
subject to argument promotions in the absence of a
prototype, and then you'd be calling malloc() with the
promoted type rather than the expected type.


OTOH, you're not going to find such a pathological implementation in the
real world. There is NO *good* reason for making size_t shorter than
unsigned int on a hosted implementation (and freestanding implementations
need not provide malloc in the first place).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #27
On Fri, 12 Nov 2004 12:56:29 +0000, Dan Pop wrote:
In <pa****************************@netactive.co.uk> Lawrence Kirby <lk****@netactive.co.uk> writes:
On Thu, 11 Nov 2004 18:02:13 +0000, Herbert Rosenau wrote:
On Thu, 11 Nov 2004 14:20:14 UTC, Da*****@cern.ch (Dan Pop) wrote:
....
Nope, it doesn't. It returns whatever type was specified in its
declaration (which needs not be a prototype declaration). A function
called without a *declaration* in scope is implicitly declared as
returning int.


Except in C99.


In C99 this whole discussion is pointless: calling malloc without a
declaration in scope no longer invokes undefined behaviour, a diagnostic
is required.


Certainly, but the discussion didn't make this clear.

Lawrence

Nov 14 '05 #28

In article <cn**********@sunnews.cern.ch>, Da*****@cern.ch (Dan Pop) writes:
In <cn*********@news4.newsguy.com> mw*****@newsguy.com (Michael Wojcik) writes:

There's also the case where stdlib.h is not included but the code
supplies its own prototype for malloc. No constraint is violated
(by the use of malloc without a cast), so the implementation need
not issue a diagnostic, but the code still invokes undefined
behavior.


I can't see any undefined behaviour if the code supplies the correct
prototype for malloc. Which is perfectly possible, because there are
several other headers defining size_t.


I had forgotten about the C90 7.1.7 exception to the "declaring
identifiers in the standard library" UB rule (7.1.3). Though I note
that the actual text in 7.1.7 is:

Provided that a library function can be declared without reference
to any type defined in a header, it is also permissible to declare
the function, either explicitly or implicitly, and use it without
including its associated header.

Read literally, that would exclude providing your own declaration for
malloc, even if you had included another header that defined size_t.
The text says "without reference to any type defined in a header" -
it makes no mention of whether such a header has been included.

I suspect that's an error in the standard, and the intent was more
along the lines of "without reference to any type defined in a header
not included prior to the declaration of the library function". (I
note Phillipp Dopichaj made this same observation here in 1999, but
I was unable to find any further discussion of the issue here or in
comp.std.c.)

--
Michael Wojcik mi************@microfocus.com

The surface of the word "profession" is hard and rough, the inside mixed with
poison. It's this that prevents me crossing over. And what is there on the
other side? Only what people longingly refer to as "the other side".
-- Tawada Yoko (trans. Margaret Mitsutani)
Nov 14 '05 #29
In <cn*********@news3.newsguy.com> mw*****@newsguy.com (Michael Wojcik) writes:

In article <cn**********@sunnews.cern.ch>, Da*****@cern.ch (Dan Pop) writes:
In <cn*********@news4.newsguy.com> mw*****@newsguy.com (Michael Wojcik) writes:
>
>There's also the case where stdlib.h is not included but the code
>supplies its own prototype for malloc. No constraint is violated
>(by the use of malloc without a cast), so the implementation need
>not issue a diagnostic, but the code still invokes undefined
>behavior.


I can't see any undefined behaviour if the code supplies the correct
prototype for malloc. Which is perfectly possible, because there are
several other headers defining size_t.


I had forgotten about the C90 7.1.7 exception to the "declaring
identifiers in the standard library" UB rule (7.1.3). Though I note
that the actual text in 7.1.7 is:

Provided that a library function can be declared without reference
to any type defined in a header, it is also permissible to declare
the function, either explicitly or implicitly, and use it without
including its associated header.

Read literally, that would exclude providing your own declaration for
malloc, even if you had included another header that defined size_t.
The text says "without reference to any type defined in a header" -
it makes no mention of whether such a header has been included.


The text doesn't say "without reference to any type defined in *any*
header", it clearly talks about the header that is not included. There
is nothing wrong if I declare malloc using the definition of size_t
provided by <stdio.h>, I'm still not referring to any type defined in
<stdlib.h>, the standard doesn't require anywhere that the declaration
of malloc() must use the definition of size_t provided by the header
associated with malloc().

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #30
mw*****@newsguy.com (Michael Wojcik) writes:
I had forgotten about the C90 7.1.7 exception to the "declaring
identifiers in the standard library" UB rule (7.1.3). Though I note
that the actual text in 7.1.7 is:

Provided that a library function can be declared without reference
to any type defined in a header, it is also permissible to declare
the function, either explicitly or implicitly, and use it without
including its associated header.

Read literally, that would exclude providing your own declaration for
malloc, even if you had included another header that defined size_t.
The text says "without reference to any type defined in a header" -
it makes no mention of whether such a header has been included.


But you *can* declare malloc without reference to a type defined
in a header:
void *malloc();
--
Ben Pfaff
email: bl*@cs.stanford.edu
web: http://benpfaff.org
Nov 14 '05 #31

In article <cn**********@sunnews.cern.ch>, Da*****@cern.ch (Dan Pop) writes:
In <cn*********@news3.newsguy.com> mw*****@newsguy.com (Michael Wojcik) writes:
I had forgotten about the C90 7.1.7 exception to the "declaring
identifiers in the standard library" UB rule (7.1.3). Though I note
that the actual text in 7.1.7 is:

Provided that a library function can be declared without reference
to any type defined in a header, it is also permissible to declare
the function, either explicitly or implicitly, and use it without
including its associated header.

Read literally, that would exclude providing your own declaration for
malloc, even if you had included another header that defined size_t.
The text says "without reference to any type defined in a header" -
it makes no mention of whether such a header has been included.


The text doesn't say "without reference to any type defined in *any*
header", it clearly talks about the header that is not included.


It most certainly does not. It says "a header"; to refer only to the
header that would have provided a declaration for the function, it
would have used the definite article.

The second paragraph of 7.1.7 is misworded. That's all there is to it.

--
Michael Wojcik mi************@microfocus.com

Pocket #16: A Ventriloquist's "Helper" -- Recordings for Divers Occasions,
especially cries to put in the mouths of enemies -- "God Bless Captain
Vere!" "Les jeux sont faits!" &c. -- Joe Green
Nov 14 '05 #32

In article <87************@benpfaff.org>, Ben Pfaff <bl*@cs.stanford.edu> writes:
mw*****@newsguy.com (Michael Wojcik) writes:
Read literally, that would exclude providing your own declaration for
malloc, even if you had included another header that defined size_t.


But you *can* declare malloc without reference to a type defined
in a header:
void *malloc();


Yes, yes, fine. You could not call malloc with only such a
declaration in scope, with an argument that was neither a type
compatible with size_t nor promoted to such a type under the default
promotions. I really don't care. What I found moderately
interesting is that the text of 7.1.7 is wrong.

--
Michael Wojcik mi************@microfocus.com

Vinegar keeps more flies away than honey does.
Nov 14 '05 #33
On Fri, 12 Nov 2004 11:35:12 -0800, Ben Pfaff wrote:
mw*****@newsguy.com (Michael Wojcik) writes:
I had forgotten about the C90 7.1.7 exception to the "declaring
identifiers in the standard library" UB rule (7.1.3). Though I note
that the actual text in 7.1.7 is:

Provided that a library function can be declared without reference
to any type defined in a header, it is also permissible to declare
the function, either explicitly or implicitly, and use it without
including its associated header.

Read literally, that would exclude providing your own declaration for
malloc, even if you had included another header that defined size_t.
The text says "without reference to any type defined in a header" - it
makes no mention of whether such a header has been included.


But you *can* declare malloc without reference to a type defined in a
header:
void *malloc();


However this isn't portable. C90 6.1.2.6 says:

"All declarations that refer to the same object or function shall have
compatible type; otherwise the behavior is undefined.

And C90 6.5.4.3 says for function declaration compatibility:

"If one type has a parameter type list and the other is specified by a
function declarator that is not part of a function definition and that
contains an empty identifier list, the parameter list shall not have an
ellipsis terminator and the type of each parameter shall be compatible
with the type that results from the application of the default argument
promotions."

Essentially if the the default argument promotions change the type of
size_t then simply having the declaration void *malloc() in a program
results in undefined behaviour, even if you don't call malloc().

There is an assumption here that standard library functions have an
implicit declaration for a user-defined declaration one to be incompatible
with for 6.1.2.6. 6.1.2.6 does apply to declarations in different
translation units, but standard library functions are tricky in this
respect.

Lawrence
Nov 14 '05 #34
Lawrence Kirby <lk****@netactive.co.uk> writes:
On Fri, 12 Nov 2004 11:35:12 -0800, Ben Pfaff wrote:
But you *can* declare malloc without reference to a type defined in a
header:
void *malloc();


However this isn't portable. C90 6.1.2.6 says:

"All declarations that refer to the same object or function shall have
compatible type; otherwise the behavior is undefined.


Thanks for the insightful reading. I had never mentally
connected those paragraphs in that way, but it seems clear that
you are correct.
--
"It would be a much better example of undefined behavior
if the behavior were undefined."
--Michael Rubenstein
Nov 14 '05 #35
In <87************@benpfaff.org> Ben Pfaff <bl*@cs.stanford.edu> writes:
mw*****@newsguy.com (Michael Wojcik) writes:
I had forgotten about the C90 7.1.7 exception to the "declaring
identifiers in the standard library" UB rule (7.1.3). Though I note
that the actual text in 7.1.7 is:

Provided that a library function can be declared without reference
to any type defined in a header, it is also permissible to declare
the function, either explicitly or implicitly, and use it without
including its associated header.

Read literally, that would exclude providing your own declaration for
malloc, even if you had included another header that defined size_t.
The text says "without reference to any type defined in a header" -
it makes no mention of whether such a header has been included.


But you *can* declare malloc without reference to a type defined
in a header:
void *malloc();


Indeed, but the C standard doesn't guarantee that this is a *correct*
declaration for malloc. Admittedly, it would fail only on pathological
implementations, but using it would ruin the strict conformance of a
program.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #36
In <cn*********@news4.newsguy.com> mw*****@newsguy.com (Michael Wojcik) writes:

In article <cn**********@sunnews.cern.ch>, Da*****@cern.ch (Dan Pop) writes:
In <cn*********@news3.newsguy.com> mw*****@newsguy.com (Michael Wojcik) writes:
>I had forgotten about the C90 7.1.7 exception to the "declaring
>identifiers in the standard library" UB rule (7.1.3). Though I note
>that the actual text in 7.1.7 is:
>
> Provided that a library function can be declared without reference
> to any type defined in a header, it is also permissible to declare
> the function, either explicitly or implicitly, and use it without
> including its associated header.
>
>Read literally, that would exclude providing your own declaration for
>malloc, even if you had included another header that defined size_t.
>The text says "without reference to any type defined in a header" -
>it makes no mention of whether such a header has been included.


The text doesn't say "without reference to any type defined in *any*
header", it clearly talks about the header that is not included.


It most certainly does not. It says "a header"; to refer only to the
header that would have provided a declaration for the function, it
would have used the definite article.

The second paragraph of 7.1.7 is misworded. That's all there is to it.


Since you seem to be the only one interpreting it that way, you may want
to take the issue to comp.std.c.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #37

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

Similar topics

34
by: Richard Hunt | last post by:
I'm sorry for asking such a silly question, but I can't quite get my head around malloc. Using gcc I have always programmed in a lax C/C++ hybrid (which I suppose is actually c++). But I have...
9
by: zerro | last post by:
Hello, I try to understand heap overflows (under Linux), but can not understand one thing with freeing memory allocated with malloc(). Here it comes: I have a program called 1.c: main() {...
10
by: pembed2003 | last post by:
Hi, If I have the folllowing: char* p = malloc(5); memset(p,-1,5); *p = 0; printf("%d\n",strlen(p)); free(p); It will print 0. Is there a way to retrive the initial size of memory
58
by: lasek | last post by:
Hi all..i'm here another time..for a simple question: #include <stdlib.h> #include <stdio.h> int main(void) { /* ** I know that someone else use different malloc ** instruction
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
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...
0
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...
0
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...

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.