473,854 Members | 1,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

malloc experiments

This program compiles fine, but are there any hidden dangers
in it, or is it ok?

Experiment 1 ############### ############### ############### #####

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

int main()
{
struct pres {
char name[25];
struct pres *next;
};

struct pres *president;

president = (struct pres *)malloc(sizeof (struct pres));

strcpy(presiden t->name, "George Washington");
president->next = (struct pres *)malloc(sizeof (struct pres));

printf("The first structure has been created:\n");
printf("preside nt->name = %s\n", president->name);
printf("next structure address = %i\n", president->next);

return 0;
}

############### ############### ############### ############### #######

--Steve

Nov 13 '05
59 5233
"Mark A. Odell" wrote:

"Simon Biber" <sb****@optusho me.com.au> wrote in
news:3f******** **************@ news.optusnet.c om.au:
strncat(preside nt->name, "George Washington", PRES_NAME_LEN - 1);


Question on style here. How does PRES_NAME_LEN improve readability versus
the orignal

struct pres {
char name[25];
struct pres *next;
};

if we use sizeof president->name instead of PRES_NAME_LEN? I see the
manifest constant as extra work without real additional clarity.


It doesn't clarify the struct declaration. However,
elsewhere in the code we find things like the above-mentioned

strncat(preside nt->name, "George Washington",
PRES_NAME_LEN - 1);

.... and this "spelling" of the third argument is superior to
a bare `24' or even `25 - 1' for the simple reason that it's
easier to alter the program to accommodate "George Herbert
Walker Bush" (26 letters, plus terminating '\0'): just change
the #define and all your worries are over. No need to go
groveling through the code looking for all occurrences of
`24' and `25' and trying to figure which need changing.

To my taste, though, it's still not a good solution. If
you come upon this strncat() call in the middle of some code
somewhere, how can you tell that `president->name' is in fact
an array of `PRES_NAME_LEN' characters? To me, the name
suggests that the array should have `PRES_NAME_LEN+ 1' elements,
but the main point would be the same even with a less equivocal
identifier: How do you know that the coder used the manifest
constant associated with `president->name' and not with some
other array altogether? The situation is analogous to the
oft-deprecated

ptr = malloc(sizeof(s truct header_type_6)) ;

.... where there's no immediate confirmation that the coder has
passed the correct type to `sizeof'.

The recommended cure for the malloc case is to write

ptr = malloc(sizeof *ptr);

.... and I'd suggest that the cure for the strncat() case should
be similar:

strncat(preside nt->name, "George Washington",
sizeof president->name - 1);

No worries about whether the argument should be `PRES_NAME_LEN'
or `PRES_NAME_LEN - 1' or perhaps `NAME_BUFFER_SI ZE - 1', and
the correctness can be established by purely local inspection.

"Almost established," anyhow, because the coder needs to
know that `president->name' is an actual array and not a pointer
to the start of an array elsewhere. But that's a burden that
C coders shoulder pretty much all the time anyhow, and we should
by now be accustomed to and wary of it.

Summary: `sizeof' is your friend most of the time, and you
should enjoy that friendship whenever it's offered.

--
Er*********@sun .com
Nov 13 '05 #21
Steve Zimmerman wrote:

Daniel Haude wrote:
On Wed, 03 Sep 2003 14:23:55 GMT,
Steve Zimmerman <st******@sonic .net> wrote
in Msg. <3F************ **@sonic.net>
This program compiles fine, but are there any hidden dangers
in it, or is it ok?

president = (struct pres *)malloc(sizeof (struct pres));


Who taught you to cast malloc()'s return value? Others have pointed out
the reasons why this is bad; I just want to know where you got the idea
from.

--Daniel


The honest answer is, "No one taught me to cast malloc()'s return value.
I've never written any code using malloc." See

http://www.c-for-dummies.com/lessons/chapter.17


Oh, dear. They also void main(). That website seems to be living up to its
name.

--
Tim Hagan
Nov 13 '05 #22
Martin Dickopp <ex************ *@zero-based.org> wrote in
news:bj******** *****@news.t-online.com:
Question on style here. How does PRES_NAME_LEN improve readability
versus the orignal

struct pres {
char name[25];
struct pres *next;
};

if we use sizeof president->name instead of PRES_NAME_LEN? I see the
manifest constant as extra work without real additional clarity.


Although I'm not the person who suggested `PRES_NAME_LEN' originally in
this thread, I still like the idea. The reason is that I prefer to
#define /all/ magic numbers in one place per file, so if this were my
code, I would have used the macro in the structure declaration, but
still referred to the size of the member as `sizeof president->name'
later.


Fair enough.

--
- Mark ->
--
Nov 13 '05 #23
Eric Sosman <Er*********@su n.com> wrote in news:3F******** *******@sun.com :
"Mark A. Odell" wrote:
Question on style here. How does PRES_NAME_LEN improve readability
versus the orignal

struct pres {
char name[25];
struct pres *next;
};

if we use sizeof president->name instead of PRES_NAME_LEN? I see the
manifest constant as extra work without real additional clarity.
It doesn't clarify the struct declaration. However,
elsewhere in the code we find things like the above-mentioned


[snip]
Summary: `sizeof' is your friend most of the time, and you
should enjoy that friendship whenever it's offered.


In the end, do I take it that you agree with me? That is, to use the
sizeof on the array and not create a manifest constant? I appreciate
Martin's desire to put all magic numbers in one place however. I might
amend this to "comment" all my magic numbers w/ a manifest constant, use
them in the definition of the size of the array, but then never use them
in the code again using only sizeof arrayname. How does this sound?

--
- Mark ->
--
Nov 13 '05 #24
"Mark A. Odell" wrote:

Eric Sosman <Er*********@su n.com> wrote in news:3F******** *******@sun.com :
"Mark A. Odell" wrote:
Question on style here. How does PRES_NAME_LEN improve readability
versus the orignal

struct pres {
char name[25];
struct pres *next;
};

if we use sizeof president->name instead of PRES_NAME_LEN? I see the
manifest constant as extra work without real additional clarity.
It doesn't clarify the struct declaration. However,
elsewhere in the code we find things like the above-mentioned


[snip]
Summary: `sizeof' is your friend most of the time, and you
should enjoy that friendship whenever it's offered.


In the end, do I take it that you agree with me? That is, to use the
sizeof on the array and not create a manifest constant?


It certainly seems we agree. There remains the problem
of an "array" that's actually a pointer (perhaps by virtue of
being passed as a function argument), but them's the breaks.
I appreciate
Martin's desire to put all magic numbers in one place however. I might
amend this to "comment" all my magic numbers w/ a manifest constant, use
them in the definition of the size of the array, but then never use them
in the code again using only sizeof arrayname. How does this sound?


Personally, I don't think I'd find it helpful. YMMV.

However, if you've got several arrays that are all supposed
to have the same number of elements, it may make sense to use
just one manifest constant for all the declarations even if you
go on to use `sizeof' everywhere else:

#define WIDE 20
#define TALL 50
int matrix[TALL][WIDE];
int row_totals[TALL];
int row_maxima[TALL];
int col_totals[WIDE];
int col_maxima[WIDE];

It's possible to eliminate the manifest constants:

int matrix[50][20];
int row_totals[ sizeof matrix / sizeof matrix[0] ];
int row_maxima[ sizeof matrix / sizeof matrix[0] ];
int col_totals[ sizeof matrix[0] / sizeof matrix[0][0] ];
int col_maxima[ sizeof matrix[0] / sizeof matrix[0][0] ];

.... but to my taste this is surpassingly ugly, and not an aid
to clarity. (Confession: When I first wrote this, I got it
backwards.)

--
Er*********@sun .com
Nov 13 '05 #25
In article <3F************ **@sonic.net>, st******@sonic. net says...
The honest answer is, "No one taught me to cast malloc()'s return value.
I've never written any code using malloc." See

http://www.c-for-dummies.com/lessons/chapter.17


Suffice it to say that you shouldn't believe everything
you find on that site.
--
Randy Howard _o
2reply remove FOOBAR \<,
_______________ _______()/ ()_____________ _______________ _______________ ___
SCO Spam-magnet: po********@sco. com
Nov 13 '05 #26
August Derleth wrote:

Daniel Haude <ha***@physnet. uni-hamburg.de> wrote

Who taught you to cast malloc()'s return value?


It's common practice in C++, one of the differences between that
language and C and one of the reasons experienced C programmers blanch
at the meaningless term 'C/C++'.

Common practice indeed, because it's REQUIRED in C++.


Brian Rodenborn
Nov 13 '05 #27
In article <3F************ ***@boeing.com> , no*****@boeing. com says...
The honest answer is, "No one taught me to cast malloc()'s return value.
I've never written any code using malloc." See

http://www.c-for-dummies.com/lessons/chapter.17


Oh, dear. They also void main(). That website seems to be living up to its
name.


I downloaded the source code archives posted there for the "book form" of
this website. It is filled with similar problems. I sent an email to the
author about some of it, I don't know how it will turn out.

--
Randy Howard _o
2reply remove FOOBAR \<,
_______________ _______()/ ()_____________ _______________ _______________ ___
SCO Spam-magnet: po********@sco. com
Nov 13 '05 #28
In article <3F************ ***@company.com >,
Default User <fi********@com pany.com> wrote:
August Derleth wrote:

Daniel Haude <ha***@physnet. uni-hamburg.de> wrote

> Who taught you to cast malloc()'s return value?


It's common practice in C++, one of the differences between that
language and C and one of the reasons experienced C programmers blanch
at the meaningless term 'C/C++'.

Common practice indeed, because it's REQUIRED in C++.


'Tis? I thought using new and delete was also an option.
dave

--
Dave Vandervies dj******@csclub .uwaterloo.ca

Generally speaking, undefined behavior invokes nethack, not Quake.
--Ben Pfaff in comp.lang.c
Nov 13 '05 #29
dj******@csclub .uwaterloo.ca (Dave Vandervies) wrote in
<bj**********@t abloid.uwaterlo o.ca>:
In article <3F************ ***@company.com >,
Default User <fi********@com pany.com> wrote:
August Derleth wrote:

Daniel Haude <ha***@physnet. uni-hamburg.de> wrote

> Who taught you to cast malloc()'s return value?

It's common practice in C++, one of the differences between that
language and C and one of the reasons experienced C programmers blanch
at the meaningless term 'C/C++'.

Common practice indeed, because it's REQUIRED in C++.


'Tis? I thought using new and delete was also an option.


The latter has no impact on the requirement to explicitly
cast malloc's return value in (here off-topic) C++.

Irrwahn
--
Sig. Sic.
Nov 13 '05 #30

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

Similar topics

2
660
by: Steve Zimmerman | last post by:
Esteemed contributors to clc: Thank you for all the responses. Experiments 2 and 3 below are identical, except that experiment 2 does not call free(), while experiment 3 does. With such a trivial program, is it safe not to call free()? Are there dangers in experiment 2 that experiment 3 avoids?
0
9751
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
10682
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10758
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10371
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7082
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
5942
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4562
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3187
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.