473,657 Members | 2,550 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2259
ma***********@g mx.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_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.
Nov 14 '05 #6
"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.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.or g> Keith Thompson <ks***@mib.or g> 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.or g> wrote in message
news:ln******* *****@nuthaus.m ib.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**********@s unnews.cern.ch> , Dan Pop <Da*****@cern.c h> 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

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

Similar topics

34
6427
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 started messing around in Plan 9, and that sort of thing is totally no go there :). Is this correct to allocate memory for my struct? It works on my computer, but I'm suspicious that I'm doing it wrong. --
9
2397
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() { char *a, *b, *c, *d, *e; a = malloc(8);
10
2305
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
3903
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
8425
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
8326
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
8845
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
8522
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,...
1
6177
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
5647
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
4173
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...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.