Google Groupes n'accepte plus les nouveaux posts ni abonnements Usenet. Les contenus de l'historique resteront visibles.

new in C?

0 vue
Accéder directement au premier message non lu

Inconnu

non lue,
25 août 1998, 03:00:0025/08/1998
à
I know this is a very newbie question but

i use c++. never really learned c. always assumed backward
compatibility. recently, i've been working on c source code.

every time i try to use dynamic allocation with new, it tells me
something is wrong.

does c have dynamic allocation? do you use new? how do you do it?

lets just say:
int *pn = new int;
something like that. how?

Tzvetan Chaliavski

non lue,
25 août 1998, 03:00:0025/08/1998
à

*sigh* you need a good C book.

> something like that. how?

operators are not part of C. use malloc()/calloc()/realloc() instead.

int *pn = (int *) malloc(sizeof(int));

later you can use realloc() to change the size of the block allocated.

--
Tzvetan Chaliavski Command Software Systems, Inc.
ce...@commandcom.com 1061 E. Indiantown Road
Phone (561)575-3200 x4197 Jupiter
Fax (561)575-3026 FL 33477

Emulov

non lue,
25 août 1998, 03:00:0025/08/1998
à
C does have dynamic memory allocation, but it is used by things like
malloc() and free(), see any standard reference, book or on-line
help...

--
*********************************************************
* EMULOV'S COMPUTER CENTRE
* computer-internet-search eninges-programming
* URL: http://www.sin.khk.be/~emulov/index_english.htm
* EMAIL: emu...@sin.khk.be
* PLEASE DON'T SEND ME ANY POSTS
*********************************************************

:I know this is a very newbie question but


:
:i use c++. never really learned c. always assumed backward
:compatibility. recently, i've been working on c source code.
:
:every time i try to use dynamic allocation with new, it tells me
:something is wrong.
:
:does c have dynamic allocation? do you use new? how do you do it?
:
:lets just say:
: int *pn = new int;

:something like that. how?

John Gordon

non lue,
25 août 1998, 03:00:0025/08/1998
à
(NewBie) writes:

>does c have dynamic allocation? do you use new? how do you do it?

c does not have "new". c has malloc(), which is a function that will
dynamically allocate memory. unlike new, though, it will not
automatically call any sort of initialization routines (constructors).

malloc() is called with a single argument, which is the size of the
memory space requested. generally this is expressed as the number
of objects requested multiplied by the size of the object. example:

int *i;

i = malloc(10 * sizeof(int));

malloc will return NULL when it can't get any more space.
errorchecking left to the reader.

---
John Gordon "No Silicon Heaven? Preposterous! Where would
gor...@osiris.cso.uiuc.edu all the calculators go?" -- Kryten, Red Dwarf

jik-

non lue,
25 août 1998, 03:00:0025/08/1998
à
> :I know this is a very newbie question but
> :
> :i use c++. never really learned c. always assumed backward
> :compatibility. recently, i've been working on c source code.
> :
> :every time i try to use dynamic allocation with new, it tells me
> :something is wrong.
> :
> :does c have dynamic allocation? do you use new? how do you do it?
> :
> :lets just say:
> : int *pn = new int;
> :something like that. how?

No, C does not use new. afaik that is an OOP only concept.
In C you use malloc/realloc/free and the sizeof op.
I recomend reading up on C, there is no backward compatability, C/C++
are two seperate entirely different languages.


Arun Jayendran

non lue,
25 août 1998, 03:00:0025/08/1998
à
NewBie () wrote:
: I know this is a very newbie question but

: i use c++. never really learned c. always assumed backward
: compatibility. recently, i've been working on c source code.

: every time i try to use dynamic allocation with new, it tells me
: something is wrong.

: does c have dynamic allocation? do you use new? how do you do it?

: lets just say:
: int *pn = new int;
: something like that. how?

Use malloc() and free() to dynamically allocate and free memory.

For eg:
int *pn;
pn = (int *) malloc(sizeof(int));

and

free(pn);

Arun


Michael Wynne

non lue,
25 août 1998, 03:00:0025/08/1998
à

Hi,

C the "language", does not actually have dynamic memory
allocation at all. Everything about a C program is static, ie
it's known about at compile time. However dynamic data
structures are created at run time using a variety of functions
available from the "Standard" library. The 2 most common
being
malloc(), and free().

Get a good reference on C to find out what functionality is
available in the standard library.

You will also generally find many more functions available for
dynamic memory allocation, most are value added additions
by the vendor, many are very useful.

C++ was designed to be a superset of C. Most well written
C programs will compile under a C++ compiler with few minor
changes. If you read the introduction to Stroustrup's latest edition
of the C++ reference manual he actually states all this, so before
any language wars erupt, they are his words not mine.

Hope this helps

Michael

Arjan Bokx

non lue,
25 août 1998, 03:00:0025/08/1998
à
In article <35E2FC72...@commandcom.com>, Tzvetan Chaliavski

<URL:mailto:ce...@commandcom.com> wrote:
>
> int *pn = (int *) malloc(sizeof(int));
>

In article <6ruvn3$feq$1...@engnews2.Eng.Sun.COM>, Arun Jayendran


<URL:mailto:ja...@Sun.COM> wrote:
>
> int *pn;
> pn = (int *) malloc(sizeof(int));

Do not cast the value returned by malloc. It is unnecessary at best, and
dangerous at worst.


Arjan Bokx
--
(replace underscore with dash for email reply)
(vervang underscore door minstreepje voor antwoord per epost)


Charles LaCour

non lue,
25 août 1998, 03:00:0025/08/1998
à

--
Increase the Peace!
Charles LaCour
cla...@mci2000.com

Arjan Bokx wrote in message ...


>In article <35E2FC72...@commandcom.com>, Tzvetan Chaliavski
><URL:mailto:ce...@commandcom.com> wrote:
>>
>> int *pn = (int *) malloc(sizeof(int));
>>
>
>In article <6ruvn3$feq$1...@engnews2.Eng.Sun.COM>, Arun Jayendran
><URL:mailto:ja...@Sun.COM> wrote:
>>
>> int *pn;
>> pn = (int *) malloc(sizeof(int));
>
>Do not cast the value returned by malloc. It is unnecessary at best, and
>dangerous at worst.
>

I would say it's harmless at best and unnecessary at worst.
The idea that you may forget to include <stdlib.h> (which is the only
argument I've heard) seems pretty benign.

Martin Ambuhl

non lue,
25 août 1998, 03:00:0025/08/1998
à

Mike McCarty wrote in message <6rvmq1$ljg$1...@relay1.dsccc.com>...
|In article <6rvmhe$f...@bgtnsc02.worldnet.att.net>,
|Craig Franck <clfr...@worldnet.att.net> wrote:
|)jik- <fr...@sprintmail.com> wrote:
|)
|)>> :does c have dynamic allocation? do you use new? how do you do it?
|)>> :
|)>> :lets just say:
|)>> : int *pn = new int;
|)>> :something like that. how?
|)>
|)> No, C does not use new. afaik that is an OOP only concept.
|)
|)Operator new was introduced into C++ as a programming convenience. It
|)doesn't have anything directly to do with any OOP concept.
|
|It existed in Pascal before C++ or OOP existed.
=======
It is true that Wirth was responsible for new, but his proposal predates
Pascal by a bit. His paper is
Wirth, N.: On Certain Basic Concepts of Programming Languages, Stanford
University, Computer Science Dept. Tech. Rept., CS65, May 1, 1967.

The days when you see a pre-ETH address for Wirth are rare indeed.

Note that it was common to use recursion to do allocation in ALGOL60.
Perlis and Standish proposed templates in 1966 and 1967 and Wirth's
suggestion built on that and the PL/1 pseudo-templates with based
attributes.

Wirth proposed ALGOL structures (Pascal derives from ALGOL) :
new A(a); Create an instance of the structure A and name it a

PL/1 adopted his proposal as
ALLOCATE A SET(P); Create an instance of structure A and refer
to it through the pointer P
FREE P;

Notice that Standish introduced parameterized templates in his Ph.D.
thesis at Carnegie in 1967, and Perlis had Formula Algol up and running
in 1966 with dynamic allocation before Wirth introduced the word "new"
for allocation.

It was also common for ALGOL60 implementations to have for coroutines
resume P(args); resume P with the parameters args. The args
are not actually needed, because they
the activation record for P, which could be
created by an initial call or by
allocate P(args); create an activation record for P using args
free P; delete the coroutine activation record.

Isn't it wonderful how all this stuff was exciting and new when C++ came
out? Oops. C++ hasn't figured out coroutines yet. That's ok. We've
only had 30 years.


Craig Franck

non lue,
26 août 1998, 03:00:0026/08/1998
à
jik- <fr...@sprintmail.com> wrote:

>> :does c have dynamic allocation? do you use new? how do you do it?

>> :
>> :lets just say:


>> : int *pn = new int;

>> :something like that. how?


>
> No, C does not use new. afaik that is an OOP only concept.

Operator new was introduced into C++ as a programming convenience. It


doesn't have anything directly to do with any OOP concept.

--
Craig
clfr...@worldnet.att.net
Manchester, NH
The most savage controversies are those about matters as to
which there is no good evidence either way. -- Bertrand Russell


Mike McCarty

non lue,
26 août 1998, 03:00:0026/08/1998
à
In article <6rvmhe$f...@bgtnsc02.worldnet.att.net>,
Craig Franck <clfr...@worldnet.att.net> wrote:
)jik- <fr...@sprintmail.com> wrote:
)
)>> :does c have dynamic allocation? do you use new? how do you do it?
)>> :
)>> :lets just say:
)>> : int *pn = new int;
)>> :something like that. how?
)>
)> No, C does not use new. afaik that is an OOP only concept.
)
)Operator new was introduced into C++ as a programming convenience. It
)doesn't have anything directly to do with any OOP concept.

It existed in Pascal before C++ or OOP existed.

Mike
--
----
char *p="char *p=%c%s%c;main(){printf(p,34,p,34);}";main(){printf(p,34,p,34);}
This message made from 100% recycled bits.
I don't speak for DSC. <- They make me say that.

Jack Klein

non lue,
26 août 1998, 03:00:0026/08/1998
à
On Tue, 25 Aug 1998 19:24:43 -0700, "Charles LaCour" <cla...@MCI2000.com>
wrote:

> --

Please do not put your signature starting with "--" at the top of your post.
Many newsreaders (mine included) automatically strip off everything after the
line with "--" when replying. Put it at the end where it belongs.

> Increase the Peace!
> Charles LaCour
> cla...@mci2000.com
>
> Arjan Bokx wrote in message ...
> >In article <35E2FC72...@commandcom.com>, Tzvetan Chaliavski
> ><URL:mailto:ce...@commandcom.com> wrote:
> >>
> >> int *pn = (int *) malloc(sizeof(int));
> >>
> >
> >In article <6ruvn3$feq$1...@engnews2.Eng.Sun.COM>, Arun Jayendran
> ><URL:mailto:ja...@Sun.COM> wrote:
> >>
> >> int *pn;
> >> pn = (int *) malloc(sizeof(int));
> >
> >Do not cast the value returned by malloc. It is unnecessary at best, and
> >dangerous at worst.
> >
>
> I would say it's harmless at best and unnecessary at worst.
> The idea that you may forget to include <stdlib.h> (which is the only
> argument I've heard) seems pretty benign.

<Jack>

There are many platforms where sizeof(int) != sizeof(void *), so this error
can be fatal.

</Jack>


Soren Sandmann Pedersen

non lue,
26 août 1998, 03:00:0026/08/1998
à
Arjan Bokx writes:

> Do not cast the value returned by malloc. It is unnecessary at best,
> and dangerous at worst.

How can it be dangerous?

User923005

non lue,
26 août 1998, 03:00:0026/08/1998
à
Soren Sandmann Pedersen:
You forgot to include stdlib.h.

You put your compiler warnings at a low level because you are tired of the
compiler screaming at the cheezy factory supplied headers.

It compiles [cleanly -- so you think]. It links. Without a worry in the
world, you run the program.

Undefined behavior rears its ugly head. First, your computer whistles the star
spangled banner and hops around the room. Then, Scott Nudds flies out of your
left nostril. There he is, dripping in mucus, and grinning at you.

YOU DON'T CALL THAT DANGEROUS!?


--
C-FAQ ftp sites: ftp://ftp.eskimo.com ftp://rtfm.mit.edu
Hypertext C-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
C-FAQ Book: ISBN 0-201-84519-9.
Want Software? Algorithms? Pubs? http://www.infoseek.com

Alf_...@logitech.com

non lue,
26 août 1998, 03:00:0026/08/1998
à
In article <35e5f4d...@news.mindspring.com>,

(NewBie) wrote:
> I know this is a very newbie question but
>
> i use c++. never really learned c. always assumed backward
> compatibility. recently, i've been working on c source code.
>
> every time i try to use dynamic allocation with new, it tells me
> something is wrong.
>
> does c have dynamic allocation? do you use new? how do you do it?
Yes, it's called 'malloc'.

> lets just say:


> int *pn = new int;

> something like that. how?

/* Allocate one int and pn is set to point to that int */
int * pn = (int *)malloc(sizeof(int));
*pn = 13;

/* Allocate an array of 12 int values. pn2 is set to point to that array */
pn2 = (int *)calloc(12,sizeof(int));

You can also do:

pn2 = (int *)malloc(12 * sizeof(int));

but there are two differences: i) calloc initializes the array to all bits
zero. If it is an array of pointers this is not necessarily the same as a 0
pointer. Make sure that if the data type you calloc() is a pointer or a
struct containing a pointer you must set all such pointer values to 0 after
you have calloc()'ed the array.

malloc doesn't initialize the memory area at all, you get a raw memory block
containing 'random' values.

ii) If size_t is restricted on your system, calloc may allocate more than the
corresponding malloc() call can do.

struct HS {
char b[16384];
};

struct HS * hsp1 = (struct HS *)malloc(sizeof(struct HS)*8);

might fail to allocate 8 entries since 8 * 16384 may exceed the allowable
range for size_t even if 16384 does not. Unfortunately since this gives
overflow in the argument you get no indication from malloc() that anything's
wrong. You simply get a much smaller block than you expected!

struct HS * hsp2 = (struct HS *)calloc(8,sizeof(struct HS));

might succeed and give you that array of 8 struct elements even if the
malloc() above failed.

To release a block of memory (similar to delete) you call free().

free(pn);

The pointer pn is invalid after free() so *pn isn't a good idea after such a
call. It is therefore a good habit to set that pointer to 0 after you called
free().

free(pn);
pn = 0;

If you have malloc()'ed or calloc()'ed a block of memory you can later resize
that block. If the new size is smaller than old size the block has shrunk and
if the new size is larger the block has grown.

int * arr = (int *)malloc(5 * sizeof(int));
/* arr of 5 ints allocated */

/* Ooops...I need 10, 5 is not enough */ int * arr2 = (int
*)realloc(10*sizeof(int)); /* arr is now invalid and can be set to 0 or set
to point to arr2. However, if realloc failed, arr2 would be 0 and the old
value arr is still valid. It is therefore not a good idea to store the return
value of realloc directly into the arr pointer but first check that it is
non-zero before you do that */ if (arr2 == 0) failure(); arr = arr2;

/* Ok, I don't need 10 any more, 3 is enough */
arr2 = (int *)realloc(3 * sizeof(int));
if (arr2 == 0) failure();
arr = arr2;

/* I don't need the array any more */
free(arr);
arr = 0;

Consider a realloc call such as this:

ptr2 = realloc(ptr, new_size);

Note that ptr2 may or may not be equal to ptr. Essentially realloc() will
attempt to use the same area as given on input and therefore return ptr as
return value whenever the conditions for doing so is good. Reasons why
realloc() may reallocate the area and so give you a pointer to a new area can
be any or several of the following:

1. The memory block pointed to by ptr is too small and cannot be enlarged.
However, it is possible to allocate a new block that is large enough to
contain all the data.

2. The memory block pointed to by ptr is really too big, even if you split
the block you get a big 'hole' in the heap. However, there are already a
'hole' in the heap that fit better to contain the new data. The C runtime
library may use this opportunity to move the data to that new place so that
the block pointed to by ptr can be freed. For example if the heap looks like
this:

|XXXXXXXX111XXXXXXX22222222222ppp33333333333XXXXXXXX|

Where X's means allocated space while 111, 22222 and 33333 are 'holes' or
unused space in the heap and 'ppp' is the block allocated and pointed to by
p. Assume that the resized block fits in hole 1. Then the library may figure
that moving the data from p to 1 means that 2 and 3 can be connected together
into one big hole. Thus this move is a good thing. This argument applies even
if the new size is equal to the old size.

In short: A program should ALWAYS assume that the return value ptr2 from
realloc() is different the input argument ptr.

When realloc finds out that it wants to move to a different block it will
automatically move data from the original place to the new place. Essentially
it will do the same as:

memcpy(ptr2,ptr,len);

Where len is the minimum value of old_size and new_size. If new size is larger
than old size it means that some data area is left uninitialized and this area
contain raw undefined data. If new size is smaller than old size it means that
some data is 'forgotten'. However, this shouldn't matter since you tell the
system that you don't need those data any more when you realloc() the area.

After this move, realloc() will automatically free up the old data area
pointed to by ptr. This means that you should NEVER call free(ptr); if you
have given ptr as input argument to realloc(). Simply spoken: realloc()
function as a free() function for all practical purposes in this context.

Another note about realloc. Be aware if you have pointers pointing into the
block you realloc. It is a bad idea to have lots of those pointers around if
you plan to realloc the area, since those other pointers are invalid. Instead
it is then better to have a fixed data structure which is allocated and which
contains a pointer to the realloc()'ed area. All other references should then
go to that fixed data structure and use that data structure as an indirection
level. The reason is that you can then simply have ONE pointer which points
to the memory area that can shrink or grow in size. That single pointer is
much easier to update and maintain than if you have tons of them.

A final note for C++ programmers.

malloc() is not exactly equivalent to the operator new. If you have
overloaded operator new you know that you can write a function called
'operator new'. This function is not the same as the operator called 'new'.
Specifically in C++ when you write:

x = new T;

The following steps occur:

1. The function new is called. This function may throw an exception in which
case step 2 is not done.
2. The constructor for T is called.

The function new is roughly equivalent to malloc() but the operator new is
not as outlined above. Specifically, malloc() will never call any constructor
(there are no constructors in C).

Similar observations holds for free vs. delete. Also for delete there is a
big difference between the function delete and the operator delete. The
operator delete will first call the destructor for the type based on the data
type of the pointer given as argument and then when that destructor is done
it will call the function delete. The function delete is roughly equivalent
to free() but the operator delete is not. Specifically there are no
destructors in C.

Data types in C++ that do not have constructors or destructors will
essentially behave the same as C's malloc/free when you use new/delete.

Question: Can you mix new/delete and malloc/free? For example if you do
strdup() of a string, can you delete [] that string? On most implementations
that I have seen that is perfectly ok since the function delete is
implemented by calling free() and a string is a character array and doesn't
have any constructor. However, I am not sure if it is ALWAYS possible to
depend on such features. Whenever I write a C++ program and I need strdup
functionality I will therefore do one of the following:

1. Use free() instead of delete [] on that string. 2. write my own strdup
which uses new char[strlen(s) + 1]; instead of standard C library strdup.

Alf

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp Create Your Own Free Member Forum

tst...@my-dejanews.com

non lue,
26 août 1998, 03:00:0026/08/1998
à
In article <35E30556...@sprintmail.com>,

jik- <fr...@sprintmail.com> wrote:
> > :I know this is a very newbie question but
> > :
> > :i use c++. never really learned c. always assumed backward
> > :compatibility. recently, i've been working on c source code.
> > :
> > :every time i try to use dynamic allocation with new, it tells me
> > :something is wrong.
> > :
> > :does c have dynamic allocation? do you use new? how do you do it?
> > :
> > :lets just say:

> > : int *pn = new int;
> > :something like that. how?
>
> No, C does not use new. afaik that is an OOP only concept.

I'd say new was a C++ operator, you can certainly write non-OOP code in C++
and still use new.

> In C you use malloc/realloc/free and the sizeof op.
> I recomend reading up on C, there is no backward compatability, C/C++
> are two seperate entirely different languages.

I'm sure a lot of people will be surprised by that, although not 100% there is
backward compatibility. You can still program in C++ as (though not exactly)
you would in C. I believe you can still use all the C functions in C++.

Backwards compatability means that the older code should compile under the new
compiler, What the original poster was trying to do could be termed forward
compatability; ie he was trying to use a new feature under an old
implementation.

--
Tristan Styles

Failure is not an option
It is Standard Operating Procedure

tst...@my-dejanews.com

non lue,
26 août 1998, 03:00:0026/08/1998
à
In article <4kKE1.46$eW6....@news.mci2000.com>,

"Charles LaCour" <cla...@MCI2000.com> wrote:
>
>
> --
> Increase the Peace!
> Charles LaCour
> cla...@mci2000.com
>
> Arjan Bokx wrote in message ...
[snip]

> >
> >Do not cast the value returned by malloc. It is unnecessary at best, and
> >dangerous at worst.
> >
>
> I would say it's harmless at best and unnecessary at worst.
> The idea that you may forget to include <stdlib.h> (which is the only
> argument I've heard) seems pretty benign.
>

Until you do it yourself and waste half a day tracking it down.
( No, I haven't )

Richard Krehbiel

non lue,
26 août 1998, 03:00:0026/08/1998
à
Jack Klein wrote in message <35f995c9...@netnews.worldnet.att.net>...
>On Tue, 25 Aug 1998 19:24:43 -0700, "Charles LaCour" <cla...@MCI2000.com>
>wrote:
>
>> --
>

>Please do not put your signature starting with "--" at the top of your
post.
>Many newsreaders (mine included) automatically strip off everything after
the
>line with "--" when replying. Put it at the end where it belongs.

F^^*&^ing Microsoft Outlook Express prepares a reply message by prepending
your signature. I always have to cut it and paste it to the end. Like this
message.

(Not remotely topical, I know.)

--
Richard Krehbiel, Kastle Systems, Arlington VA USA
ri...@kastle.com (work) or ri...@mnsinc.com (personal)

Lawrence Kirby

non lue,
26 août 1998, 03:00:0026/08/1998
à
In article <6rvmq1$ljg$1...@relay1.dsccc.com>
jmcc...@sun1307.spd.dsccc.com "Mike McCarty" writes:

>In article <6rvmhe$f...@bgtnsc02.worldnet.att.net>,
>Craig Franck <clfr...@worldnet.att.net> wrote:
>)jik- <fr...@sprintmail.com> wrote:
>)
>)>> :does c have dynamic allocation? do you use new? how do you do it?
>)>> :
>)>> :lets just say:
>)>> : int *pn = new int;
>)>> :something like that. how?
>)>
>)> No, C does not use new. afaik that is an OOP only concept.
>)
>)Operator new was introduced into C++ as a programming convenience. It
>)doesn't have anything directly to do with any OOP concept.
>
>It existed in Pascal before C++ or OOP existed.

Nevertheless in C++ new calls any constructor for the type which connects it
to C++'s OOP support and means there's more to C++'s new operator than
Pascal's.

--
-----------------------------------------
Lawrence Kirby | fr...@genesis.demon.co.uk
Wilts, England | 7073...@compuserve.com
-----------------------------------------


Lawrence Kirby

non lue,
26 août 1998, 03:00:0026/08/1998
à
In article <35f995c9...@netnews.worldnet.att.net>
jack...@worldnet.att.net "Jack Klein" writes:

...

>There are many platforms where sizeof(int) != sizeof(void *), so this error
>can be fatal.

There can be problems even if they are the same size. Consider a processor
like the 68000 which has separate data and address registers. Consider what
would happen if an integer return value was returned in a data register and
a pointer return value was returned in an address register. Also consider
what would happen if conversion from int to a pointer required a change of
representation (bit pattern), or alternatively a change between pointer
types required this.

Stephan Wilms

non lue,
26 août 1998, 03:00:0026/08/1998
à
NewBie wrote:
>
> i use c++. never really learned c. always assumed backward
> compatibility. recently, i've been working on c source code.
>
> every time i try to use dynamic allocation with new, it tells me
> something is wrong.
>
> does c have dynamic allocation? do you use new? how do you do it?
>
> lets just say:

> int *pn = new int;
> something like that. how?

Hi NewBie,

The "malloc()" and "free()" technique of C has already been mentioned
multiple times. But I guess you should address the more general problem
of not knowing C very well. Please be aware that C and C++ are
*different* programming languages. The similarities are very misleading
and continually cause confusion with newsbies.

Please try to learn C the *good* way by taking a C course or by
reading a good book on learning C. Here's a very good book that
I can recommend:
C Programming: A Modern Approach.
K.N.King.
W.W.Norton & Company, 1996.
ISBN 0-393-96945-2

Stephan
(initiator of the campaign against grumpiness in c.l.c)

Stephan Wilms

non lue,
26 août 1998, 03:00:0026/08/1998
à
Alf_...@logitech.com wrote:
>
> > lets just say:
> > int *pn = new int;
> > something like that. how?
>
> /* Allocate one int and pn is set to point to that int */
> int * pn = (int *)malloc(sizeof(int));
> *pn = 13;

I'd like to add two notes here, that I consider to be important:

1) *Always* check the return value of "malloc()" against NULL.
Desaster and Pandemonium will very likely be the result of
omitting the test and using a NULL pointer.

2) The cast of the "malloc()" return value is totally *unnecessary*.
A "void*" will automatically convert to any other data object
pointer type. And additionally the cast will hide the error
of having forgotten to include the appropriate header file.

> i) calloc initializes the array to all bits
> zero. If it is an array of pointers this is not necessarily the same as a 0
> pointer.

Yes, this is one of the two theoretical problems with "calloc()":
1) It might fail to initialise pointers to NULL (theoretically
possible but unlikely)
2) Similarely it might fail to initialise floating point values
to 0.0, if the bit patter for 0.0 is not all bits 0.

> Unfortunately since this gives
> overflow in the argument you get no indication from malloc() that anything's
> wrong. You simply get a much smaller block than you expected!

My advice: try to use a good compiler with the warning level set to
the most pedantic choice available. There's a good chance that it
will warn about the automatic conversion to a lower precision.

> The pointer pn is invalid after free() so *pn isn't a good idea after such a
> call. It is therefore a good habit to set that pointer to 0 after you called
> free().

Yes, it is a good habbit, but "*pn" is illegal in both cases: after
you've freed the pointer and after you've assigned NULL.

Ari Lukumies

non lue,
27 août 1998, 03:00:0027/08/1998
à
Emulov wrote:
>
> *********************************************************
> * EMULOV'S COMPUTER CENTRE
> * computer-internet-search eninges-programming

What does 'eninges' mean? :)

AriL
--
*DO NOT* send me email unless I ask you to.
I read the answers where I ask the questions.
This may also help some other people.

Ari Lukumies

non lue,
27 août 1998, 03:00:0027/08/1998
à
Tzvetan Chaliavski wrote:

>
> NewBie wrote:
> >
> > does c have dynamic allocation? do you use new? how do you do it?
> >
> > lets just say:
> > int *pn = new int;
>
> *sigh* you need a good C book.
>
> > something like that. how?
>
> operators are not part of C. use malloc()/calloc()/realloc() instead.

Says What? My ANSI spec has two (at least) tables that have the word
'operator' in them. One is titled 'Operators in C' and the other
'Operator precedence and associativity in C'. Did they drop operators in
ISO 9899 or something? Will I ever be able to assign a value again... :)

r...@cs.wisc.edu

non lue,
27 août 1998, 03:00:0027/08/1998
à
In article <6rvsk0$4...@news-central.tiac.net>,

"Martin Ambuhl" <mam...@tiac.net> wrote:
>
> It is true that Wirth was responsible for new, but his proposal predates
> Pascal by a bit. His paper is
> Wirth, N.: On Certain Basic Concepts of Programming Languages, Stanford
> University, Computer Science Dept. Tech. Rept., CS65, May 1, 1967.

This technical report can be found at

http://elib.stanford.edu/Dienst/UI/2.0/Describe/stanford.cs/CS-TR-67-65

> Wirth proposed ALGOL structures (Pascal derives from ALGOL) :
> new A(a); Create an instance of the structure A and name it a

As I read the paper, new is really a keyword introducing the declaration;
so new (integer) i; declares an integer variable i without dynamic allocation.
He also occasionally uses an Algol like notation where new (A) a; is replaced
by just A a; and so I'm not sure that this actually corresponds to new in
Pascal or C++. On the other hand, there was an example that looked
like overloading the type name as two different constructors.

He does propose that structures could always be dynamically allocated,
so that a declaration like new (A) a; would dynamically allocate an A and
assign the reference to it to a (any variable of type A would be a reference
to an A). I believe that this idea was used for records in Algol W, which he
proposed with Hoare as a successor to Algol 60.

> Isn't it wonderful how all this stuff was exciting and new when C++ came
> out? Oops. C++ hasn't figured out coroutines yet. That's ok. We've
> only had 30 years.

Rumor has it that some useful stuff got done before C++ was invented.

--
MJSR

Tzvetan Chaliavski

non lue,
27 août 1998, 03:00:0027/08/1998
à
Ari Lukumies wrote:
>
> Tzvetan Chaliavski wrote:
> >
> > NewBie wrote:
> > >
> > > does c have dynamic allocation? do you use new? how do you do it?
> > >
> > > lets just say:
> > > int *pn = new int;
> >
> > *sigh* you need a good C book.
> >
> > > something like that. how?
> >
> > operators are not part of C. use malloc()/calloc()/realloc() instead.
>
> Says What? My ANSI spec has two (at least) tables that have the word
> 'operator' in them. One is titled 'Operators in C' and the other
> 'Operator precedence and associativity in C'. Did they drop operators in
> ISO 9899 or something? Will I ever be able to assign a value again... :)

who knows - you may be unable ;)

anyways - bad english ;)

--
@*** Finagle's Laws (No 1 of 4) ***
If an experiment works, something has gone wrong.

0 nouveau message