A C showstopper

C

Chris M. Thomasson

Richard Harter wrote: [...]
It would be useful if there were a sprintf variant that does not
require the user to supply a buffer but which takes care of
allocation and returns a pointer to the resulting formatted
string.
There is, it's called snprintf.

I believe it's called `asprintf'
asprintf isn't available on all compilers.

Yeah, I know. Too bad it's not. Oh well, shi% happens.



C isn't portable. To write
portable C, you have to reinvent the wheel. To reinvent the wheel
properly, you need to be able to write English in addition to
effective C, and very few people here have the ability to construct a
complex sentence.

To construct an asprintf, you must construct it on top of an snprintf
if you're using a C99 compliant compiler, or else either recreate the
logic of printf. You have to scan for percents and sum the length of
strings and determine the string length of numbers. I suppose you
could use Malcolm's value of 30.
You then have to stress test.

Well, you don't really have to recreate `printf()'. You can use the hack
code I presented here:


http://clc.pastebin.com/f31279cba


It's certainly easier than recreating `printf()'. Whether or not it's
actually practical, well, that another matter.



To use the "hacks" presented here, you have to read the code line by
line to make sure the hacker hasn't fucked up.
;^)




As a personal matter, I
don't like to read most code written by others, since their aesthetic
is usually not mine (I found John Nash's code most pleasant on the
other hand). I'd rather code my own, with longer identifiers and
overall a more elegant way of expression...not that it's perfect and
bug free.
C is great in worlds without strings. That would be an operating
system kernel. If you want to write C, learn how to develop operating
systems.

Well, I have to use a low-level language like C for some things that are not
related to kernel programming.



Don't mess up military veterans' benefits, small businesses,
or schools with this language.

Yikes!
 
C

Chris M. Thomasson

[...]
There is, and I mentioned it in the OP. It's asprintf, and I
implemented it in 1991. It's available in the GNU compiler. My code
wasn't a "hack".

I am not sure I would call the following pseudo-code examples "hacks":

http://groups.google.com/group/comp.lang.c/msg/530d1bd4156e1927

http://groups.google.com/group/comp.lang.c/msg/169710a0cea76ce8




Now, yes, I agree that the following is a hack:

http://clc.pastebin.com/f31279cba



It was a documented solution which keeps on
mallocing, freeing the malloc, and mallocing again until the sprintf
is completed or the remalloc fails.

It's a shame that you basically had to re-implement the internal machinery
of `printf()'.
 
C

Chris McDonald

spinoza1111 said:
I'm afraid your comprehension is challenged, cowboy.

Wow! Someone take "your" seat on the ferry, again, Ed?


<more tripe snipped>

Perhaps your BFF Herb has already written the solution for you.
You could always commune with him, and you your apprise himm of how often
he's discussed here?

All you're saying, cowboy, is that "any" problem can be solved by C in
Turing's sense. But as we know, this is bullshit.

No, I didn't say that - are you reading impaired too?
Don't, for a minute, claim to state what I said

(or to parody your style "don't you lecture me").

**** you, asshole.

Just grow up Ed, else we'll all treat you like the trolling fool that you are.
 
K

Keith Thompson

Chris McDonald said:
Just grow up Ed, else we'll all treat you like the trolling fool
that you are.

Chris, what exactly is stopping you from treating him like the
trolling fool that he is now?

He's not going to change his behavior. You can. Please stop
feeding the troll.
 
S

spinoza1111

[...]
There is, and I mentioned it in the OP. It's asprintf, and I
implemented it in 1991. It's available in the GNU compiler. My code
wasn't a "hack".

I am not sure I would call the following pseudo-code examples "hacks":

http://groups.google.com/group/comp.lang.c/msg/530d1bd4156e1927

http://groups.google.com/group/comp.lang.c/msg/169710a0cea76ce8

Now, yes, I agree that the following is a hack:

http://clc.pastebin.com/f31279cba
It was a documented solution which keeps on
mallocing, freeing the malloc, and mallocing again until the sprintf
is completed or the remalloc fails.

It's a shame that you basically had to re-implement the internal machinery
of `printf()'.

Yes, it's a crying shame that I had to do it over and do it right. And
C is such a great language, too!
 
S

spinoza1111

Chris, what exactly is stopping you from treating him like the
trolling fool that he is now?

He's not going to change his behavior.  You can.  Please stop
feeding the troll.

As I have said, the grammar of "troll" is isomorphic to "Jew" in anti-
Semitic tracts. It derives from Nordic racist texts, and it fulfills
here the function of racism: unifying the community against the
outsider, no matter how that outsider is marked...here by his ability
to write above a small lower bound of complexity in an unusual
combination with programming skill somewhat above the norm, and the
fact that he was programming C when you were shitting your pants.

Your use of "trolling" is itself "trolling" by your own definition,
since you dishonestly address another with a comment about me in order
to elicit a response from me.

You assert your membership in a community dishonestly by labeling a
person who has raised a valid technical flaw in C for discussion,
because you either don't have the skills to address this problem, or
else you're afraid of bullying if your solution has been found in
error.
 
C

Chris McDonald

Chris, what exactly is stopping you from treating him like the
trolling fool that he is now?
He's not going to change his behavior. You can. Please stop
feeding the troll.


Ed trolling to hear the sound of his own voice is one thing,
but Ed's throwing hissy fits and abusing people is another.

Sorry Keith, but it's not your newsgroup, either.
 
S

spinoza1111

[...]
BTW, how many of you find that the overall idea contained within the
hack I
whipped up might be "useful"?- Hide quoted text -
I implemented it in 1991, kid.

Hey, thanks for the compliment! You know, it still makes my day when
somebody wants to check my ID when I am purchasing alcohol.

;^)
So it's useful.
Agreed.

Now all you have to do is change variables to Hungarian

There can be a "downside" to Hungarian notation. This is very contrived
example of course but it could possibly happen. Think of prefixing a bunch
of signed int variables with 'int' (e.g., `intMyVar'). Then for whatever
reason you decide to change them to unsigned variables. Well, you're going
to have to change every variable name's prefix to `uint' or something that
represents the variables unsigndness, so to speak.

Boo hoo. What, are you still using edlin to edit? In a modern editor,
case-sensitively changing int to uint while examining each change is
baby stuff. You can use a regex to automate the change.

I used systematic naming conventions in IBM 1401 SPS, when my editor
was an IBM 026 keypunch. You young whippersnappers moan and groan
about having to change things using fancy editors. I used to have to
walk to the computer center in the snow uphill both ways (etc.)
 
C

Chris M. Thomasson

Chris M. Thomasson said:
Chris M. Thomasson said:
Chris M. Thomasson said:
LOL! Well, it does work if you're platform supports something like the
NUL device.

Humm, I suppose you could also use a dummy file.


[...]


Here is another version of the program which uses a temporary file as a
"fallback" just in case the file open fails with the standard names for
some platforms NUL device:
______________________________________________________________________ [...]
int
stdnull_init(void)
{
if (! g_stdnull)
{
g_stdnull = fopen("/dev/nul", "w");
if (! g_stdnull)
{
g_stdnull = fopen("nul", "w");
if (! g_stdnull)
{
g_stdnull = tmpfile();
if (! g_stdnull)
{
return 0;
}
}
}
}
return 1;
}
[...]


I should open the file using "r+" instead of "w". Sorry about that
non-sense.

;^/
 
C

Chris M. Thomasson

Boo hoo.
lol.




What, are you still using edlin to edit? In a modern editor,
case-sensitively changing int to uint while examining each change is
baby stuff. You can use a regex to automate the change.
I used systematic naming conventions in IBM 1401 SPS, when my editor
was an IBM 026 keypunch. You young whippersnappers moan and groan
about having to change things using fancy editors.

Na, it's just that we are all hardcore super lazy bastards!

=^D



I used to have to
walk to the computer center in the snow uphill both ways (etc.)

Let me guess, you were also barefoot right? Just kidding!

:^)
 
S

spinoza1111

And if you documented the code it must be okay.

No. But if one documents the code PRIOR to coding, one does a better
job in my experience. See the free source code for my compiler. It can
be downloaded from Apress without buying my book, unfortunately and
boo hoo for me.

I code slow because I document prior, and I felt guilty for having to
bill a client for writing documentation. When, a few years prior, I'd
used True Basic to develop hydrostatic evaluation, I got the product
done faster although I had to create my own gui engine, since True
Basic supported strings without any nonsense.

One should be able to post C code here and expect it to run with all
compilers and on all platforms. Were C as good as Java, this would
indeed be possible. But as it is, one has to specify all sorts of
crazy command line options and compilers that will work. Now isn't the
ineluctable conclusion from this, that C most egregiously sucks?

When I started out, studly Dudley programmers in Chicago's Loop,
working for insurance companies like Prudential, clung to assembler
language precisely because they didn't want to feel like de-sexed
organization men (one such programmer said he and his mates brought
binoculars to work in order to watch hippies making love in Grant
Park, and that is just...sad). But the hard fact was that they were
more productive in Cobol, despite the numerous deficiencies of that
language (all global variables all the time, etc.)

C is at best a generalized assembler and for this reason it is
inappropriate to use it anywhere save in writing an operating system.

If you want to code in C, write an OS. If your employer sucks, form a
labor union. Anything else is mostly passive-aggression.
 
S

spinoza1111

Spinoza1111is the name associated with your postings.  According
to rumor, that barking dog, the name endowed upon you by your
parents is Edward Nilges. However your true name, the one is your
very essence, is He who barks at the moon.  Deal with it.


The trouble is that neither of the two methods that you mentioned
are entirely satisfactory because they require re-evaluating the
arguments.  I expect that you will immediately appreciate why
this is problematic.  I have no idea what the GNU code does but I
wouldn't be surprised if they put a layer on top of snprintf.

Oops. Thanks for pointing that out.

If an evaluation has side effects as in mySprintF("%s\n", p++) the way
to handle this would be making a pass through the format string while
evaluating as varargs all of the arguments. You shall have to make a
table of "final" pointers and lengths, and then use this table to do
the actual formatting.

You're going to have to malloc the table. If it is unbounded in the
general case, and it is, you're going to need to use malloc and
remalloc to expand it.

My goal is to stay withing the Unfriendly Confines of the C machine,
aka the C Nightmare. Truly heroic in my case, since I hate C. Rather
like Parsival inside Klingsor's unholy realm.
 
S

spinoza1111

Wow!  Someone take "your" seat on the ferry, again, Ed?

<more tripe snipped>

Perhaps your BFF Herb has already written the solution for you.
You could always commune with him, and you your apprise himm of how often
he's discussed here?


No, I didn't say that - are you reading impaired too?
Don't, for a minute, claim to state what I said

(or to parody your style "don't you lecture me").


Just grow up Ed, else we'll all treat you like the trolling fool that you are.

You have a strange notion of maturity, one that I saw first in the
1970s in structured walkthroughs. Structured walkthroughs were when
effective necessarily critical of a central tenet of modern
capitalism: that managers, merely because they are managers, know
everything (cf. in this connection John Kenneth Galbraith's essay "The
Economics of Innocent Fraud). Therefore, the effectiveness of
structured walkthroughs in many organizations was destroyed, in part
by *redefinining* what it means to be a grownup!

That is: the truth-telling, independent grownup, by pushing back
against management in the structured walkthrough, rapidly was coded in
this era as the "disruptive" element whose "pushback" (as it was known
within IBM and NASA) was delaying fulfillment of deadlines, deadlines
that were all-important because they were the only way for the MBA
types to know if they weren't being fucked over by the help (where
this concern is foregrounded when you **** the help over).

"Maturity" rapidly became what Viennese call *schlamperei*, which is
untranslatable but roughly means "going along to get along", "not
rocking the boat", and "not biting the hand that feeds" (as if a
paycheck were a gift).

Tests for "maturity" were normalized for example to tests for "bad
language" in an increasingly Fundamentalist America in which the 1973
movie The Exorcist had translated all dissent into a form of cursing
and swearing and Satanism.

The result? Far from even "reinventing the wheel" in C, something that
would be constructive, you seem here to be making no progress, and
making the same mistakes over and over again, while marginalizing
people like Schildt and Navia...who in a just world would be the
leaders of this group and not its scapegoats.

I'm on topic, and I create interesting and somewhat useful threads in
this intellectual slum. Like Falstaff, I am witty in myself and the
cause of wit that is in other men, both in the sense of a levity that
is lacking in Heathfield's posts, and an alternate older meaning of
wit as intelligence, since I make you clowns think for a change. I can
even code C that occasionally even works. You should stump up a
collection and pay me to post, even as Heathfield is probably being
paid to post by his publisher, or the CIA.
 
K

Keith Thompson

Chris McDonald said:
Ed trolling to hear the sound of his own voice is one thing,
but Ed's throwing hissy fits and abusing people is another.

Sorry Keith, but it's not your newsgroup, either.

I never said it was. I have no authority here; I just offer my
opinion and my advice.

I suggest that his "throwing hissy fits and abusing people" does not
require a response. If you ignore him, he probably won't go away,
but he'll be much easier to ignore.
 
O

Old Wolf

It would be useful if there were a sprintf variant that does not
require the user to supply a buffer but which takes care of
allocation and returns a pointer to the resulting formatted
string.

How does it allocate the memory? Plenty
of devices that are programmed in C,
use various allocation strategies other
than a "malloc" or equivalent. This function
would be unnecessarily constraining, and
shouldn't be in the C standard. (It could
be in something like POSIX though). For the
same reason, strdup() isn't in C.
And, of course, snprintf isn't part of C90.

C90 was deficient in this area; C99 fixed it.
What more do you want?

In C99 you can implement the Nilgewater
second suggestion of pre-parsing the input
to determine how much memory is needed.

He has declared he is going to reinvent the wheel anyway..
 
O

Old Wolf

All of that said, calling snprintf twice is still a hack because
every argument gets evaluated twice.

You would put it in a function, call
it my_asprintf() or something. Inside
that function you can use the C99
va_copy mechanism to be able to use
the arguments twice.

I'd be surprised if someone hasn't
posted code on the thread already!
(haven't read it all yet)
 
O

Old Wolf

Actually nobody has posted code yet for
implementing asprintf in C99, here it is:


#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

char *my_asprintf(char const *fmt, ...)
{
va_list ap1, ap2;
char *p = NULL;
int len;

va_start(ap1, fmt);
va_copy(ap2, ap1);
len = vsnprintf(NULL, 0, fmt, ap1);
va_end(ap1);

if ( len > 0 )
p = malloc(len);

if ( p )
vsprintf(p, fmt, ap2);

va_end(ap2);
return p;
}
 
P

Phil Carmody

In this line of code snprintf fails to complete the production of
the output string. All it produces is the length of the string.



Here, knowing the buffer size, snprintf can produce the output
string.

The buffer size as was, yes. However, a signal handler's
changed the first char pointed to by argN from a '\0' to a ' '
in the meantime... ;-)

Phil
 
P

Phil Carmody

Chris McDonald said:
Ed trolling to hear the sound of his own voice is one thing,
but Ed's throwing hissy fits and abusing people is another.

One is best ignored, and the other is best ignored?
Not seeing a difference there.
Sorry Keith, but it's not your newsgroup, either.

It isn't, but I know that the two Chris' are >this< close to
being temporarily killfiled because all I ever see from them
are responses to Ed Bilges. (The other one's worse, though,
if that makes you feel happy.)

Phil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,266
Messages
2,571,075
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top