468,463 Members | 1,988 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,463 developers. It's quick & easy.

Is this a good habit?

Hi,

It seems pretty common to return pointers to a static array, for
example:

char *capitalize( char *name )
{
static char buf[MAX_STRING_LENGTH];

sprintf( buf, "%s", name );
if ( *buf >= 'a' && *buf <= 'z' )
*buf += 'A' - 'a';

return buf;
}

But when I do something like this, I like to instead keep a static
pointer and malloc it the first time, to save space in whatever bank
static memory is stored in, since I have this vague idea that if too
much space is used in static memory bad things will happen? So I do
this instead:

char *capitalize( char *name )
{
static char *buf;

if ( !buf )
{
buf = malloc( MAX_STRING_LENGTH );
if ( !buf ) return name;
}

sprintf( buf, "%s", name );
if ( *buf >= 'a' && *buf <= 'z' )
*buf += 'A' - 'a';

return buf;
}

Here is how I analyze both methods as far as efficiency:

* the 2nd version uses less space in delicate "static memory" (not sure
what that's called)
* the 1st is much faster on the first call
* the 1st is slightly faster the other calls (assuming the first time,
malloc worked)
* the 1st does not assume the OS will do appropriate cleanup on exit,
as the 2nd does
* the 1st is quicker to type

I wonder which method is really best. I suppose it depends on how big
MAX_STRING_LENGTH is. I assume for instance one wouldn't want to
casually declare multi-hundred-kilobyte static arrays?

Thanks for any help =)

Jul 27 '06
62 3593

In article <11*********************@b28g2000cwb.googlegroups. com>, we******@gmail.com writes:
Snis Pilbor wrote:
EventHelix.com wrote:
Snis Pilbor wrote:
It seems pretty common to return pointers to a static array, for
example:

>
IMHO, Use of static variables inside functions is not a good idea. You
will end up with code that is not thread safe. The function will
misbehave if multiple concurrently running threads are invoking the
function with static variables.
Yes, of course, it goes without saying in either case one must exercise
caution.

What the hell is *WRONG* with you people.
We know how to think.
Review what EventHelix is
saying. If you need to run in a multithreaded environment then static
solution *CANNOT WORK*. Let me repeat: *CANNOT WORK*.
Really? How odd, as I have numerous counterexamples in code that's
used every day. Of course, the callers of such functions have to
exercise some caution, but it works with no problems whatsoever.

This may come as a surprise to you, Paul, but there are techniques
for managing shared resources in concurrent environments.

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

If Mokona means for us to eat this, I, a gentle person, will become
angry! -- Umi (CLAMP & unknown translator), _Magic Knight Rayearth_
Jul 28 '06 #51

In article <11*********************@b28g2000cwb.googlegroups. com>, "Ancient_Hacker" <gr**@comcast.netwrites:
Michael Wojcik wrote:
I'm sorry, but this isn't clear. Are you claiming that "a dozen C
compilers" constitutes "most C implementations",

We've been over this before.
And you still haven't learned.
I've been saddled with using C since the
very early days, so it's been my misfortune to intimately know
[a pointless list of implementations].
How nice for you. Many of us here - myself included - could present
similarly long lists. They would be equally irrelevant.

Either you believe a handful of C implementations constitutes "most"
such implementations, in which case I'm afraid you're mistaken; or
you're attempting to support your claims with arguments you know to
be bogus, which does nothing to impress those of us who know better.

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

Shakespeare writes bombast and knows it; Mr Thomas writes bombast and
doesn't. That is the difference. -- Geoffrey Johnson
Jul 28 '06 #52

In article <11**********************@s13g2000cwa.googlegroups .com>, "Ancient_Hacker" <gr**@comcast.netwrites:
>
I do get a bit miffed by folks that are consistently intellectually
dishonest.
Pot, kettle, albedo.

--
Michael Wojcik mi************@microfocus.com
Jul 28 '06 #53

J. J. Farrell wrote:
[]
>
Of course it can work, and it works correctly in many programs. It
cannot work if more than one thread need to concurrently do the quantum
of 'call the function and use the results'. If the design of the
program prevents that happening, or if an associated mutex is required
to be held before using the function, then it works correctly.
as another poster noted it doesn't take threads to make it unsafe.
(the example given was a printf() like:
printf("%s %s\n",capitalize(firstname),capitalize(lastname) );
>
Whether it's the best or optimum way to do it is another question, and
I'd almost always say it's not. But as Snis says, C has the flexibility
to allow it to be done this way if it is appropriate for whatever
reason. Most of the times I've found it appropriate are when a library
of such code already exists, and its functionality is now needed in a
limited and controlled way in a threaded program.
I agree, it is not a generally safe way to deal with this problem.

[]
The original C model didn't have the concept of multiple threads in a
single address space, since it was based on the original UNIX concept
of forked processes with private address space.
But the problem is not limited to multiple threads.

Ed

Jul 28 '06 #54
On 27 Jul 2006 14:52:34 -0700, in comp.lang.c , "Ancient_Hacker"
<gr**@comcast.netwrote:
>I'd consider CDC 6600's, 7600's, Vax 11/780's (Which was definitely a
mainframe, at least in size) as "mainframes".
Bizarre. The 11/780 is quite definitely a mini.

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jul 28 '06 #55
On 27 Jul 2006 15:10:23 -0700, in comp.lang.c , "Ancient_Hacker"
<gr**@comcast.netwrote:
>For what its worth, I recall one of the earlier MSC implementations
(possibly 5.1) did indeed insert zero-initialised storage into the
binary. After all, if it had been part-initialised to nonzeros then
creating it from scratch could have been expensive at runtime.

You're still not getting the big distinction between initialized data
and uninitialized data.
/I/ am, but I don't think you are. Automatics (which are the only sort
that /can/ be uninitialised) are created at runtime, generally on the
stack or maybe in registers if small enough.

You seem to be talking about file-scope variable,s which /are/
initialised, even if not explicitly.
>global variables that do
not have the "= something" business are a whole different kettle of
fish. All the compiler has to do is define a label and bump a BSS
size variable.
Er, these /must/ be initialised. The language spec requires it.
>For a little more insight-- the whole BSS segment business goes back to
the IBM 7090 days,
This is of course quite offtopic, and quoting reams of stuff I can
read for myself on wikipedia (yuck) or in any of the myriad books on
my shelves won't win you any brownie points.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jul 28 '06 #56

Mark McIntyre wrote:
On 27 Jul 2006 14:52:34 -0700, in comp.lang.c , "Ancient_Hacker"
<gr**@comcast.netwrote:
I'd consider CDC 6600's, 7600's, Vax 11/780's (Which was definitely a
mainframe, at least in size) as "mainframes".

Bizarre. The 11/780 is quite definitely a mini.
Well, opinions will differ, but IMHO anything that is four racks wide,
needs special power hookup, needs lots of airconditioning, is placed in
a raised-floor computer room, costs over $150K, has its own
minicomputer built-in as a boot and diagnostic device, has tape drives
and line printers attached, has an operator assigned to run it, falls
into the (low end) of the "mainframe" category.

True, the Vax line eventually would be squeezed into little beige
shoeboxes, but the original 780 took several trips with a forklift to
move.

Jul 29 '06 #57

Mark McIntyre wrote:
On 27 Jul 2006 15:10:23 -0700, in comp.lang.c , "Ancient_Hacker"
<gr**@comcast.netwrote:
You're still not getting the big distinction between initialized data
and uninitialized data.

/I/ am, but I don't think you are. Automatics (which are the only sort
that /can/ be uninitialised) are created at runtime, generally on the
stack or maybe in registers if small enough.

You seem to be talking about file-scope variable,s which /are/
initialised, even if not explicitly.
Ah, I now see where we diverged. Yes, file scope variables are set to
zero,
but in all the compilers I've worked with, which as a rough guess would
cover about 77% of all the binaries ever generated, there's a little
snippet of code in the C startup code that initializes them to zero.
As differentiated from the compiler having explicitly output enough
binary zeroes to fill up the variables. As most computers can zero
memory a few decades faster than they can read zeroes off a disk, it's
a win-win situation-- smaller executables and faster program startup.

..
>
Er, these /must/ be initialised. The language spec requires it.
yes, as explained above, by the C startup code.

Jul 29 '06 #58
Ancient_Hacker wrote:
Mark McIntyre wrote:
>On 27 Jul 2006 15:10:23 -0700, in comp.lang.c , "Ancient_Hacker"
<gr**@comcast.netwrote:
>>You're still not getting the big distinction between initialized data
and uninitialized data.
/I/ am, but I don't think you are. Automatics (which are the only sort
that /can/ be uninitialised) are created at runtime, generally on the
stack or maybe in registers if small enough.

You seem to be talking about file-scope variable,s which /are/
initialised, even if not explicitly.

Ah, I now see where we diverged. Yes, file scope variables are set to
zero,
but in all the compilers I've worked with, which as a rough guess would
cover about 77% of all the binaries ever generated, there's a little
From the list you've given in the past, I doubt it. I've not listed any
C compilers targeting embedded system (I bet you have never heard of the
TMS320C25 nor the TMS320C80), you don't seem to have done any targeting
the PPC, not the 68000, not the Z80, nor lots of others.
snippet of code in the C startup code that initializes them to zero.
As differentiated from the compiler having explicitly output enough
binary zeroes to fill up the variables. As most computers can zero
memory a few decades faster than they can read zeroes off a disk, it's
a win-win situation-- smaller executables and faster program startup.
That's as maybe. However, most of us here don't claim to have
encountered the majority of implementations.
--
Flash Gordon
Still sigless on this computer.
Jul 29 '06 #59

Flash Gordon wrote:
Ancient_Hacker wrote:
Mark McIntyre wrote:
On 27 Jul 2006 15:10:23 -0700, in comp.lang.c , "Ancient_Hacker"
<gr**@comcast.netwrote:
>You're still not getting the big distinction between initialized data
and uninitialized data.
/I/ am, but I don't think you are. Automatics (which are the only sort
that /can/ be uninitialised) are created at runtime, generally on the
stack or maybe in registers if small enough.

You seem to be talking about file-scope variable,s which /are/
initialised, even if not explicitly.
Ah, I now see where we diverged. Yes, file scope variables are set to
zero,
but in all the compilers I've worked with, which as a rough guess would
cover about 77% of all the binaries ever generated, there's a little

From the list you've given in the past, I doubt it. I've not listed any
C compilers targeting embedded system (I bet you have never heard of the
TMS320C25 nor the TMS320C80), you don't seem to have done any targeting
the PPC, not the 68000, not the Z80, nor lots of others.
Oh, I just got tired recollecting. Lesse: Apple MPW C for the 68000
and PPC,
then CodeWarrior C for PPC, then Microsoft and Borland C, but I already
listed those, then WATCOM C, then Microchip C for the PIC16x series,
then TI C for the 32x series (in a cochlear implant), then Some
godawful C Motorola recommended for the DSP56xxx series (outside CPU
for cochlear implant), before that, Symantec (Urp) C and gcc for the
program that drove the 56000. For all of the latter ones the program
and data had to fit into a 1 or 2 Megabyte flash ROM, and the data had
to fit at run time in the on-chip 64K fast RAM, so you can be sure we
scoured the link map looking for dumb allocations.

That's as maybe. However, most of us here don't claim to have
encountered the majority of implementations.
Well I guess it depends how you count them: by implementations or by
programming seats. I havent done a marketing survey, but just by
weighing the questions on the internet, I suspect the ones I've
listed above cover at least 80% of the seats. Just gcc and Microsoft
Visual C prolly cover 75%. I'd love to see some actual figures.

Jul 29 '06 #60
>Flash Gordon wrote:
>... most of us here don't claim to have
encountered the majority of implementations.
In article <11*********************@s13g2000cwa.googlegroups. com>
Ancient_Hacker <gr**@comcast.netwrote:
>Well I guess it depends how you count them: by implementations or by
programming seats.
There are other ways to count as well (e.g., "number of binaries
used" or "number of invocations of binaries generated"), although
your two here are probably the best. Of course, if you are going
to count "total implementations", you also have to pin down whether
to count implementations that were never used in any sort of
production capacity, such as student projects in compiler classes,
or alpha and/or beta releases of commercial compilers.
>I havent done a marketing survey, but just by weighing the questions
on the internet, I suspect the ones I've listed above cover at
least 80% of the seats. Just gcc and Microsoft Visual C prolly
cover 75%.
Here at Wind River, we would hope that Diab gets a few more. :-)

On another note: while we are mentioning ancient, strange
implementations, there is one I am curious about, and another I
will mention.

I never used this first one myself: Leor Zolman's "BDS C" for CP/M.
A friend of mine had it and used it, but I never asked whether it
had an equivalent of a "bss" section. (I would be unsurprised
whether it had it or not.)

Whitesmiths C for the Z80 (also CP/M): this one was particularly
obnoxious in that there was no "uninitialized global data". If
you compiled, e.g.:

bar.c: int global; f() { global = 2; }
main.c: main() { f(); exit(0); }

you would get an "undefined symbol" error at link-time for "global".
You had to explicitly initialize "global" to 0, which of course
put it in the data segment.

(I remmber this problem because it was so aggravating. It took me
hours, maybe even a whole day, to figure out why certain globals
were "undefined" and others were not. The documentation said that
the compiler used the def/ref model, so I had carefully written
the code this way, rather than relying on the Unix-style "common"
model, and yet it still did not link. The documentation simply
failed to mention that a "def" was not a "def" unless it was
initialized! The "extern" keyword was simply ignored.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (4039.22'N, 11150.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Jul 29 '06 #61
In article <11*********************@s13g2000cwa.googlegroups. com"Ancient_Hacker" <gr**@comcast.netwrites:
Well, opinions will differ, but IMHO anything that is four racks wide,
needs special power hookup, needs lots of airconditioning, is placed in
a raised-floor computer room, costs over $150K, has its own
minicomputer built-in as a boot and diagnostic device, has tape drives
and line printers attached, has an operator assigned to run it, falls
into the (low end) of the "mainframe" category.

True, the Vax line eventually would be squeezed into little beige
shoeboxes, but the original 780 took several trips with a forklift to
move.
The 780 we had (serial number 38) was indeed quite heavy, but not as
heavy as a mainframe. We had no problem to get it to the third floor
of the building (*). Special strengthening was not needed. The floor
was indeed raised, but that was more so to allow easy cabling between
the computers in the computer room (at first two 11's and the 780,
later a few 750's were added), and the raising was done using not so
very strong wood (it is now sagging, so it has to be redone). It had
tape drives and a line printer attached to it (at first, later the
tapes were handled by one of the 750's as was the printing), but there
was no operator assigned to run it, there was not even a console. It
ran out of itself, 24 hours each day. BSD Unix of course. There are
some nice stories about the installation of one of the 750's because
the DEC engineer wanted to install VMS, using floppies as the machine
came also without DEC disks. He was sent of to the canteen while our
staff installed BSD Unix, using temporary sharing of the Unibus.

And, no, I certainly would not have called the 780 a mainframe. At
most a super-mini.

(*) Our computer room is on the third floor. The insurance company
has the requirement that expensive computers are not on the ground
floor as that is below sea-level. So when the building was built in
1978-79 it was built with the library on the first floor, extending
to the second floor, and the computer room on the third (and highest
floor). (Eh, first floor is here the first floor above ground ;-).)
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Jul 29 '06 #62

Chris Torek wrote:
>
I never used this first one myself: Leor Zolman's "BDS C" for CP/M.
A friend of mine had it and used it, but I never asked whether it
had an equivalent of a "bss" section. (I would be unsurprised
whether it had it or not.)
BDS C had no support for initialization whatsoever. All global data was
treated as being in one great big FORTRAN Common-like block.

I don't recall even zero-initializaing that area at program startup...
;-)
-leor

Jul 30 '06 #63

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

12 posts views Thread by Arlie Rahn | last post: by
39 posts views Thread by Suresh | last post: by
45 posts views Thread by Brett | last post: by
5 posts views Thread by Phil Jones | last post: by
9 posts views Thread by Jake Montgomery | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by kmladenovski | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.