Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #104752 > unrolled thread

writing a c program to substitute text

Started byfred flintstone <fred@server.invalid>
First post2017-02-26 04:14 -0800
Last post2017-02-28 08:46 -0800
Articles 20 on this page of 86 — 21 participants

Back to article view | Back to comp.lang.c


Contents

  writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-02-26 04:14 -0800
    Re: writing a c program to substitute text fir <profesor.fir@gmail.com> - 2017-02-26 04:55 -0800
    Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-26 14:28 +0100
      Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-02-27 03:58 -0800
        Re: writing a c program to substitute text Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-02-27 13:11 +0000
          Re: writing a c program to substitute text BartC <bc@freeuk.com> - 2017-02-27 13:33 +0000
            Re: writing a c program to substitute text scott@slp53.sl.home (Scott Lurndal) - 2017-02-27 17:12 +0000
              Re: writing a c program to substitute text BartC <bc@freeuk.com> - 2017-02-27 17:59 +0000
                Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 19:05 +0100
                Re: writing a c program to substitute text scott@slp53.sl.home (Scott Lurndal) - 2017-02-27 18:37 +0000
                  Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-27 11:40 -0800
          Re: writing a c program to substitute text Manfred <noname@invalid.add> - 2017-02-27 16:03 +0100
          Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-03-01 05:33 -0800
            Re: writing a c program to substitute text "D. Aaron Sawyer" <aaron@110.net> - 2017-03-01 10:32 -0400
              Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-03-01 06:59 -0800
                Re: writing a c program to substitute text Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-03-01 15:24 +0000
                  Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-03-02 01:47 -0800
                    Re: writing a c program to substitute text Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-03-02 11:05 +0000
        Re: writing a c program to substitute text jt@toerring.de (Jens Thoms Toerring) - 2017-02-27 13:33 +0000
          Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-27 09:10 -0800
            Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 19:07 +0100
              Re: writing a c program to substitute text jt@toerring.de (Jens Thoms Toerring) - 2017-02-27 18:23 +0000
        Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 14:46 +0100
          Re: writing a c program to substitute text James Kuyper <jameskuyper@verizon.net> - 2017-02-27 09:27 -0500
            Re: writing a c program to substitute text GOTHIER Nathan <nathan.gothier@gmail.com> - 2017-02-27 15:28 +0100
              Re: writing a c program to substitute text James Kuyper <jameskuyper@verizon.net> - 2017-02-27 09:38 -0500
            Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 15:44 +0100
              Re: writing a c program to substitute text James Kuyper <jameskuyper@verizon.net> - 2017-02-27 10:36 -0500
              Re: writing a c program to substitute text Anglican <h.toms@qmul.ac.uk> - 2017-02-27 15:50 +0000
                Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 17:13 +0100
                Re: writing a c program to substitute text Malcolm McLean <malcolm.mclean5@btinternet.com> - 2017-02-27 16:30 -0800
            Re: writing a c program to substitute text fir <profesor.fir@gmail.com> - 2017-02-27 07:08 -0800
              Re: writing a c program to substitute text fir <profesor.fir@gmail.com> - 2017-02-27 07:20 -0800
                Re: writing a c program to substitute text fir <profesor.fir@gmail.com> - 2017-02-27 07:24 -0800
          Re: writing a c program to substitute text Manfred <noname@invalid.add> - 2017-02-27 16:00 +0100
          Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-27 09:22 -0800
            Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 19:11 +0100
        Re: writing a c program to substitute text John Bode <jfbode1029@gmail.com> - 2017-02-28 15:41 -0800
          solved Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-03-02 01:25 -0800
            Re: solved Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-03-02 11:28 +0100
            Re: solved Re: writing a c program to substitute text Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-03-02 10:54 +0000
              Re: solved Re: writing a c program to substitute text Manfred <noname@invalid.add> - 2017-03-02 15:28 +0100
                Re: solved Re: writing a c program to substitute text Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-03-02 14:51 +0000
              Re: solved Re: writing a c program to substitute text John Bode <jfbode1029@gmail.com> - 2017-03-02 14:18 -0800
                Re: solved Re: writing a c program to substitute text Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-03-02 23:55 +0000
                  Re: solved Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-03-14 18:32 -0700
          Re: writing a c program to substitute text Tim Rentsch <txr@alumni.caltech.edu> - 2017-04-17 07:04 -0700
      Re: writing a c program to substitute text jladasky@itu.edu - 2017-02-27 13:48 -0800
        Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-02-27 14:16 -0800
          Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-28 08:47 +0100
            Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-02-28 01:59 -0800
              Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-28 11:39 +0100
              Re: writing a c program to substitute text Richard Heathfield <rjh@cpax.org.uk> - 2017-02-28 12:03 +0000
                Re: writing a c program to substitute text BartC <bc@freeuk.com> - 2017-02-28 13:33 +0000
                  Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-28 14:43 +0100
                    Re: writing a c program to substitute text BartC <bc@freeuk.com> - 2017-02-28 13:59 +0000
                      Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-03-01 04:26 -0800
        Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 23:29 +0100
        Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-27 15:10 -0800
    Re: writing a c program to substitute text Malcolm McLean <malcolm.mclean5@btinternet.com> - 2017-02-26 06:42 -0800
      Re: writing a c program to substitute text Richard Heathfield <rjh@cpax.org.uk> - 2017-02-26 16:54 +0000
        [OT] "Mr. Man-wai Chang" <toylet.toylet@gmail.com> - 2017-02-27 00:56 +0800
      Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-26 13:36 -0800
        Re: writing a c program to substitute text Malcolm McLean <malcolm.mclean5@btinternet.com> - 2017-02-26 14:53 -0800
          Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 00:53 +0100
            Re: writing a c program to substitute text Malcolm McLean <malcolm.mclean5@btinternet.com> - 2017-02-26 17:30 -0800
              Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-26 17:44 -0800
              Re: writing a c program to substitute text Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-02-27 01:46 +0000
                Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 09:29 +0100
                  Re: writing a c program to substitute text Malcolm McLean <malcolm.mclean5@btinternet.com> - 2017-02-27 02:12 -0800
                    Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-27 13:11 +0100
      Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-02-27 04:41 -0800
        Re: writing a c program to substitute text Malcolm McLean <malcolm.mclean5@btinternet.com> - 2017-02-27 05:04 -0800
          Re: writing a c program to substitute text Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-02-27 13:25 +0000
          Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-27 09:56 -0800
    Re: writing a c program to substitute text "Mr. Man-wai Chang" <toylet.toylet@gmail.com> - 2017-02-27 01:00 +0800
    Re: writing a c program to substitute text "James R. Kuyper" <jameskuyper@verizon.net> - 2017-02-26 18:55 -0500
      Re: writing a c program to substitute text fred flintstone <fred@server.invalid> - 2017-02-28 04:20 -0800
        Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-28 14:38 +0100
          Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-28 08:33 -0800
            Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-28 19:38 +0100
              Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-28 11:40 -0800
                Re: writing a c program to substitute text David Brown <david.brown@hesbynett.no> - 2017-02-28 21:03 +0100
              Re: gcc optimization levels Noob <root@127.0.0.1> - 2017-02-28 22:55 +0100
        Re: writing a c program to substitute text "James R. Kuyper" <jameskuyper@verizon.net> - 2017-02-28 11:43 -0500
        Re: writing a c program to substitute text Keith Thompson <kst-u@mib.org> - 2017-02-28 08:46 -0800

Page 4 of 5 — ← Prev page 1 2 3 [4] 5  Next page →


#104765

FromRichard Heathfield <rjh@cpax.org.uk>
Date2017-02-26 16:54 +0000
Message-ID<o8v14e$suf$1@dont-email.me>
In reply to#104761
On 26/02/17 14:42, Malcolm McLean wrote:
> On Sunday, February 26, 2017 at 12:14:23 PM UTC, fred flintstone wrote:
>
>> Let's say that you're hard-coding a string between single quotes, for
>> example:
>>
>> 'arrow'
>>
>> , how do I declare this string to exist safely?
>>
>> Do I malloc a 1000 because someone has to make an adult decision?
>>
> No, you write a function called mystrdup(). (There will also be a strdup
> provided with your environment but it may not be available with
> certain compiler settings.
>
> char *mystdrdup(const char *str)
> {
>    size_t len - strlen(str):

ITYM size_t len = strlen(str);

>    char *answer = malloc(len + 1);
>    if(answer)
>       strcpy(answer, str);

You might as well use the fact that you know the length:

         memcpy(answer, str, len + 1);


>    else
>       /* error handling here */;

         Such as?

> C is inherently unsafe.

C is perfectly safe. It's programmers who are dangerous.

-- 
Richard Heathfield
Email: rjh at cpax dot org dot uk
"Usenet is a strange place" - dmr 29 July 1999
Sig line 4 vacant - apply within

[toc] | [prev] | [next] | [standalone]


#104766 — [OT]

From"Mr. Man-wai Chang" <toylet.toylet@gmail.com>
Date2017-02-27 00:56 +0800
Subject[OT]
Message-ID<o8v18e$te0$1@dont-email.me>
In reply to#104765
On 27/02/2017 12:54 AM, Richard Heathfield wrote:
>
>> C is inherently unsafe.
>
> C is perfectly safe. It's programmers who are dangerous.
>

Managers and directors are even more dangerous, by forcing programmers 
to work overtime while taking them to pubs to drink alcohol and smoke 
cigarettes? :)

-- 
   @~@   Remain silent! Drink, Blink, Stretch! Live long and prosper!!
  / v \  Simplicity is Beauty!
/( _ )\ May the Force and farces be with you!
   ^ ^   (x86_64 Ubuntu 9.10)  Linux 2.6.39.3
不借貸! 不詐騙! 不援交! 不打交! 不打劫! 不自殺! 請考慮綜援 (CSSA):
http://www.swd.gov.hk/tc/index/site_pubsvc/page_socsecu/sub_addressesa

[toc] | [prev] | [next] | [standalone]


#104791

FromKeith Thompson <kst-u@mib.org>
Date2017-02-26 13:36 -0800
Message-ID<ln1sukhbx2.fsf@kst-u.example.com>
In reply to#104761
Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> On Sunday, February 26, 2017 at 12:14:23 PM UTC, fred flintstone wrote:
>> Let's say that you're hard-coding a string between single quotes, for 
>> example:
>> 
>> 'arrow'
>> 
>> , how do I declare this string to exist safely?
>> 
>> Do I malloc a 1000 because someone has to make an adult decision?
>>
> No, you write a function called mystrdup(). (There will also be a strdup
> provided with your environment but it may not be available with
> certain compiler settings.

Malcolm, I'm at a loss to understand how you were able to infer that the
OP needs something like strdup.  I can't figure out just what he's
saying, but my best guess is that
    const char *s = "arrow";
or
    const char s[] = "arrow";
would be suitable.  I suggest that any speculation beyond that should
wait for a more coherent question.

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

[toc] | [prev] | [next] | [standalone]


#104794

FromMalcolm McLean <malcolm.mclean5@btinternet.com>
Date2017-02-26 14:53 -0800
Message-ID<182b9ecd-0719-4704-9118-b5a24cb022e9@googlegroups.com>
In reply to#104791
On Sunday, February 26, 2017 at 9:36:25 PM UTC, Keith Thompson wrote:
> Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> 
> Malcolm, I'm at a loss to understand how you were able to infer that the
> OP needs something like strdup.  I can't figure out just what he's
> saying, but my best guess is that
>     const char *s = "arrow";
> or
>     const char s[] = "arrow";
> would be suitable.  I suggest that any speculation beyond that should
> wait for a more coherent question.
> 
The complaint is that C string literals are "unsafe", the OP then asks
is he should malloc 1000 bytes of memory just to be safe.

Generally people think that C is unsafe because they are used to
languages where strings are higher-level objects. And in C terms
that means, "guaranteed to be on the heap".

[toc] | [prev] | [next] | [standalone]


#104796

FromDavid Brown <david.brown@hesbynett.no>
Date2017-02-27 00:53 +0100
Message-ID<o8vplm$o5a$1@dont-email.me>
In reply to#104794
On 26/02/17 23:53, Malcolm McLean wrote:
> On Sunday, February 26, 2017 at 9:36:25 PM UTC, Keith Thompson wrote:
>> Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
>>
>> Malcolm, I'm at a loss to understand how you were able to infer that the
>> OP needs something like strdup.  I can't figure out just what he's
>> saying, but my best guess is that
>>     const char *s = "arrow";
>> or
>>     const char s[] = "arrow";
>> would be suitable.  I suggest that any speculation beyond that should
>> wait for a more coherent question.
>>
> The complaint is that C string literals are "unsafe", the OP then asks
> is he should malloc 1000 bytes of memory just to be safe.

It seems to me that the OP doesn't know much about C or strings, and is 
making some wild guesses.  We can't help him until we get more 
information.  But we /can/ cause immense confusion by making bizarre 
posts about home-made strdup functions.

>
> Generally people think that C is unsafe because they are used to
> languages where strings are higher-level objects.

That's one possibility.  Most people thing "C is unsafe" because they 
don't know much about it, or how to write safe code - and they know that 
some people write unsafe C code.

> And in C terms
> that means, "guaranteed to be on the heap".
>

That is complete nonsense.  Putting something on the heap is never safer 
in any way than having it local to a function or statically allocated. 
And in particular, the safest strings are those that are constants that 
are fixed in the program - string literals.

[toc] | [prev] | [next] | [standalone]


#104810

FromMalcolm McLean <malcolm.mclean5@btinternet.com>
Date2017-02-26 17:30 -0800
Message-ID<a935c0ac-022a-4ca5-9e7a-a821785d9e68@googlegroups.com>
In reply to#104796
On Sunday, February 26, 2017 at 11:53:30 PM UTC, David Brown wrote:
> On 26/02/17 23:53, Malcolm McLean wrote:
>  
> >
> > Generally people think that C is unsafe because they are used to
> > languages where strings are higher-level objects.
> 
> That's one possibility.  Most people thing "C is unsafe" because they 
> don't know much about it, or how to write safe code - and they know that 
> some people write unsafe C code.
> 
> > And in C terms
> > that means, "guaranteed to be on the heap".
> >
> 
> That is complete nonsense.  Putting something on the heap is never safer 
> in any way than having it local to a function or statically allocated. 
> And in particular, the safest strings are those that are constants that 
> are fixed in the program - string literals.
>
No, the only way to make objects safe is to have a rigorously controlled
memory model for them. Which  means some form of managed pointer with
the object on the heap. (I know that as a micro- optimisation C++
std::strings are actually stack objects for short strings, I'm talking
generally and loosely).

In language X, which is a high level scripting language of some sort,
we'll almost certainly have a structure in memory which is essentially
a pointer, and gives memory-checked access to our object plus
intelligent lifetime management. It might have a trivial bit of 
decoration on the stack, e.g. a type field as well as memory address, 
but even that is unlikely. 

[toc] | [prev] | [next] | [standalone]


#104811

FromKeith Thompson <kst-u@mib.org>
Date2017-02-26 17:44 -0800
Message-ID<lnwpccflvs.fsf@kst-u.example.com>
In reply to#104810
Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> On Sunday, February 26, 2017 at 11:53:30 PM UTC, David Brown wrote:
>> On 26/02/17 23:53, Malcolm McLean wrote:
>> > Generally people think that C is unsafe because they are used to
>> > languages where strings are higher-level objects.
>> 
>> That's one possibility.  Most people thing "C is unsafe" because they 
>> don't know much about it, or how to write safe code - and they know that 
>> some people write unsafe C code.
>> 
>> > And in C terms
>> > that means, "guaranteed to be on the heap".
>> 
>> That is complete nonsense.  Putting something on the heap is never safer 
>> in any way than having it local to a function or statically allocated. 
>> And in particular, the safest strings are those that are constants that 
>> are fixed in the program - string literals.
>>
> No, the only way to make objects safe is to have a rigorously controlled
> memory model for them. Which  means some form of managed pointer with
> the object on the heap. (I know that as a micro- optimisation C++
> std::strings are actually stack objects for short strings, I'm talking
> generally and loosely).

More nonsense.  How is "a rigorously controlled memory model" involving
"some form of managed pointer with the object on the heap" safer than a
simple string literal (which designates an object that exists for the
entire execution of the program)?

We don't know whether a string literal satisfies the OP's requirements;
we'll have to wait for clarification on what those requirements are.

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

[toc] | [prev] | [next] | [standalone]


#104812

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2017-02-27 01:46 +0000
Message-ID<87bmto8kys.fsf@bsb.me.uk>
In reply to#104810
Malcolm McLean <malcolm.mclean5@btinternet.com> writes:

> On Sunday, February 26, 2017 at 11:53:30 PM UTC, David Brown wrote:
>> On 26/02/17 23:53, Malcolm McLean wrote:
>>
>> > Generally people think that C is unsafe because they are used to
>> > languages where strings are higher-level objects.
>> 
>> That's one possibility.  Most people thing "C is unsafe" because they 
>> don't know much about it, or how to write safe code - and they know that 
>> some people write unsafe C code.
>> 
>> > And in C terms
>> > that means, "guaranteed to be on the heap".
>>
>> That is complete nonsense.  Putting something on the heap is never safer 
>> in any way than having it local to a function or statically allocated. 
>> And in particular, the safest strings are those that are constants that 
>> are fixed in the program - string literals.
>>
> No, the only way to make objects safe is to have a rigorously controlled
> memory model for them.

You are in danger of talking at cross-purposes.  Your idea of a safe
object is one that is safe regardless of what is done with it.  David's
view of a safe object is one that is (or maybe can be) used safely.

Without a discussion about what it means for a language, program or
object to be safe or unsafe, there will be little chance of
mutual understanding.

<snip>
-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#104826

FromDavid Brown <david.brown@hesbynett.no>
Date2017-02-27 09:29 +0100
Message-ID<o90ntq$q79$1@dont-email.me>
In reply to#104812
On 27/02/17 02:46, Ben Bacarisse wrote:
> Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> 
>> On Sunday, February 26, 2017 at 11:53:30 PM UTC, David Brown wrote:
>>> On 26/02/17 23:53, Malcolm McLean wrote:
>>>
>>>> Generally people think that C is unsafe because they are used to
>>>> languages where strings are higher-level objects.
>>>
>>> That's one possibility.  Most people thing "C is unsafe" because they 
>>> don't know much about it, or how to write safe code - and they know that 
>>> some people write unsafe C code.
>>>
>>>> And in C terms
>>>> that means, "guaranteed to be on the heap".
>>>
>>> That is complete nonsense.  Putting something on the heap is never safer 
>>> in any way than having it local to a function or statically allocated. 
>>> And in particular, the safest strings are those that are constants that 
>>> are fixed in the program - string literals.
>>>
>> No, the only way to make objects safe is to have a rigorously controlled
>> memory model for them.

I agree with that statement - what I don't agree with is your idea of a
rigorously controlled memory model.

> 
> You are in danger of talking at cross-purposes.  Your idea of a safe
> object is one that is safe regardless of what is done with it.  David's
> view of a safe object is one that is (or maybe can be) used safely.
> 

Thank you for that insight.  I hadn't thought of it from that point of
view, and it gives some reasoning behind Malcolm's claims.

> Without a discussion about what it means for a language, program or
> object to be safe or unsafe, there will be little chance of
> mutual understanding.
> 

I think we can work with a rough definition - something is "safe" for a
particular purpose if you can use it reliably for that purpose without
having unexpected side-effects.  The /purpose/ is key here.  A car may
have airbags, seatbelts, automatic braking and all sorts of features to
make it safe for driving - but it is still not going to be very safe as
a boat.

In this case, the OP was asking about hard-coded strings between quotes.
 In C, you can read these - you cannot write them.  So "safe" here means
being able to reliably access them for reading, with a minimum of
unexpected side-effects (such as running out of memory, corrupting
structures, leaking resources, etc.).  Using a const*char pointer to
"arrow", or using "const char s[] = "arrow";" with program lifetime
(file scope, or function static), will give you that with the most
rigorously controlled memory model C can provide.

If the user wants to modify the string, then it's a different matter -
and more complex code is needed to be sure it is done safely.  Malcolm
is still wrong about the heap being somehow "safer" than the stack, however.


[toc] | [prev] | [next] | [standalone]


#104832

FromMalcolm McLean <malcolm.mclean5@btinternet.com>
Date2017-02-27 02:12 -0800
Message-ID<9eb280b4-776c-4461-9d7c-161b1698d1b4@googlegroups.com>
In reply to#104826
On Monday, February 27, 2017 at 8:29:43 AM UTC, David Brown wrote:
> On 27/02/17 02:46, Ben Bacarisse wrote:
> > Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> > 
> > You are in danger of talking at cross-purposes.  Your idea of a safe
> > object is one that is safe regardless of what is done with it.  David's
> > view of a safe object is one that is (or maybe can be) used safely.
> > 
> 
> Thank you for that insight.  I hadn't thought of it from that point of
> view, and it gives some reasoning behind Malcolm's claims.
> 
Ben's right. Of course char *arrow = "arrow" is safe in the sense that it
doesn't cause an immediate memory error, and in skilled hands it can
be used safely.
>
> I think we can work with a rough definition - something is "safe" for a
> particular purpose if you can use it reliably for that purpose without
> having unexpected side-effects.  The /purpose/ is key here.  A car may
> have airbags, seatbelts, automatic braking and all sorts of features to
> make it safe for driving - but it is still not going to be very safe as
> a boat.
>
I'd say you've got engineered safety - which a car has, thousands of them 
drive around the city every day with acceptable consequences - and inherent
safety. A car is inherently dangerous, because there's no way of telling it
not to crash into a pedestrian, other than the engineered system of roads
and pavements and traffic lights. A bike is inherently safe, because even if it 
does crash into a pedestrian, it doesn't have the mass or speed to cause
a fatal injury, at least usually,
> 
> In this case, the OP was asking about hard-coded strings between quotes.
>  In C, you can read these - you cannot write them.  So "safe" here means
> being able to reliably access them for reading, with a minimum of
> unexpected side-effects (such as running out of memory, corrupting
> structures, leaking resources, etc.).  Using a const*char pointer to
> "arrow", or using "const char s[] = "arrow";" with program lifetime
> (file scope, or function static), will give you that with the most
> rigorously controlled memory model C can provide.
>
But what if you try to free it? Or what if you want to strip spaces, which 90%
of the time will be a no-op? 
>
> If the user wants to modify the string, then it's a different matter -
> and more complex code is needed to be sure it is done safely.  Malcolm
> is still wrong about the heap being somehow "safer" than the stack, however.
>
ava is easier that C++, largely because Java doesn't allow objects other than
primitive and handles on the stack. C++ is harder to program because a object
could be on the heap or on the stack. C++ people have evolved ways of dealing
with that, but it's engineered safety.

[toc] | [prev] | [next] | [standalone]


#104842

FromDavid Brown <david.brown@hesbynett.no>
Date2017-02-27 13:11 +0100
Message-ID<o914th$6pv$1@dont-email.me>
In reply to#104832
On 27/02/17 11:12, Malcolm McLean wrote:
> On Monday, February 27, 2017 at 8:29:43 AM UTC, David Brown wrote:
>> On 27/02/17 02:46, Ben Bacarisse wrote:
>>> Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
>>>
>>> You are in danger of talking at cross-purposes.  Your idea of a safe
>>> object is one that is safe regardless of what is done with it.  David's
>>> view of a safe object is one that is (or maybe can be) used safely.
>>>
>>
>> Thank you for that insight.  I hadn't thought of it from that point of
>> view, and it gives some reasoning behind Malcolm's claims.
>>
> Ben's right. Of course char *arrow = "arrow" is safe in the sense that it
> doesn't cause an immediate memory error, and in skilled hands it can
> be used safely.

What do you mean, "in skilled hands"?  It is hard to be /unsafe/ with
this method - you need "skilled hands" to break it.  Of course, that
assumes you are able to correctly write "/const/ char* arrow", rather
than fail to copy the example.

>>
>> I think we can work with a rough definition - something is "safe" for a
>> particular purpose if you can use it reliably for that purpose without
>> having unexpected side-effects.  The /purpose/ is key here.  A car may
>> have airbags, seatbelts, automatic braking and all sorts of features to
>> make it safe for driving - but it is still not going to be very safe as
>> a boat.
>>
> I'd say you've got engineered safety - which a car has, thousands of them 
> drive around the city every day with acceptable consequences - and inherent
> safety. A car is inherently dangerous, because there's no way of telling it
> not to crash into a pedestrian, other than the engineered system of roads
> and pavements and traffic lights. A bike is inherently safe, because even if it 
> does crash into a pedestrian, it doesn't have the mass or speed to cause
> a fatal injury, at least usually,

Fair enough.  That is going into more detail than I did, but I agree
with it.

>>
>> In this case, the OP was asking about hard-coded strings between quotes.
>>  In C, you can read these - you cannot write them.  So "safe" here means
>> being able to reliably access them for reading, with a minimum of
>> unexpected side-effects (such as running out of memory, corrupting
>> structures, leaking resources, etc.).  Using a const*char pointer to
>> "arrow", or using "const char s[] = "arrow";" with program lifetime
>> (file scope, or function static), will give you that with the most
>> rigorously controlled memory model C can provide.
>>
> But what if you try to free it? Or what if you want to strip spaces, which 90%
> of the time will be a no-op? 

You can't "free" it - but there is no logical reason why you would try
to do so.  The same applies to any "rigorously managed" string system -
you would never call "free" from user code.  If user code is calling
functions like malloc or free directly, it is not "rigorously managed".

You cannot strip spaces from the string either - it is read-only.  It is
a fixed "hard-coded" string, just as the OP wanted.

>>
>> If the user wants to modify the string, then it's a different matter -
>> and more complex code is needed to be sure it is done safely.  Malcolm
>> is still wrong about the heap being somehow "safer" than the stack, however.
>>
> ava is easier that C++, largely because Java doesn't allow objects other than
> primitive and handles on the stack.

No, that is not the case - it is totally wrong.

First, Java is "easier" than C++ for some things, harder for others.  It
is true that it is easier to write Java code without the typical C
mistakes of failing to free heap memory or trying to free it twice.  But
modern C++ also makes it easy to write such code, using unique_ptr and
shared_ptr.  The key to Java's memory handling is its garbage collection
so that user code does not have to "free" anything, and thus cannot make
mistakes with "free" - the fact that most objects are put on the heap is
completely incidental.

In C, the safest place to put run-time data is on the stack - precisely
because you don't have to worry about freeing the memory.  (It is also
more efficient, which is a nice bonus.)  Of course you must be careful
about the sizes of data to allocate, and you typically have no
information about allocation failure.  And the allocated memory does not
live beyond the lifetime of the function.  But when stack data can be
used, it is safer than the heap because it is simpler.

> C++ is harder to program because a object
> could be on the heap or on the stack.

That does not make it harder to program.

> C++ people have evolved ways of dealing
> with that, but it's engineered safety.
> 

The C++ language has evolved more convenient ways of handling memory
safety.  Because it is part of the language, it is at least as much
"inherent safety" as the Java method - both languages have been
"engineered" to make them as safe as practical for users.

[toc] | [prev] | [next] | [standalone]


#104844

Fromfred flintstone <fred@server.invalid>
Date2017-02-27 04:41 -0800
Message-ID<ehil3aFg16sU1@mid.individual.net>
In reply to#104761
On 02/26/2017 06:42 AM, Malcolm McLean wrote:

> No, you write a function called mystrdup(). (There will also be a strdup
> provided with your environment but it may not be available with
> certain compiler settings.
>
> char *mystdrdup(const char *str)
> {
>    size_t len - strlen(str):
>    char *answer = malloc(len + 1);
>    if(answer)
>       strcpy(answer, str);
>    else
>       /* error handling here */;
>
>    return answer;
> }
>
> You call it like this
>
> char *str = mystrdup("arrow");
>
> Now the string is in heap memory, you can modify it, and it will stick
> around until you delete it. For a simple string literal, the win
> isn't very great. But if you are building a string, then  you can
> construct it in a temporary buffer, then duplicate it. The buffer
> is then free to construct the next string.
>
> C is inherently unsafe. You have to keep track of which strings are
> on the heap (so the easy answer is to say, "they all are"), and
> who "owns" each string and thus has responsibility for freeing.
>
>
>

Thanks, malcolm. The way I have it now, I have the strings to be 
substituted initialized in source code:

    const char *executable1 = "arrow";
    const char *executable2 = "mahershala";

How would the memory considerations go if these were to come off the 
command line with argv[]?
-- 
fred flintstone

[toc] | [prev] | [next] | [standalone]


#104846

FromMalcolm McLean <malcolm.mclean5@btinternet.com>
Date2017-02-27 05:04 -0800
Message-ID<c92cd5e3-05c4-485d-bab7-1b630c9d0cbe@googlegroups.com>
In reply to#104844
On Monday, February 27, 2017 at 12:41:24 PM UTC, fred flintstone wrote:
> On 02/26/2017 06:42 AM, Malcolm McLean wrote:
> 
>
> Thanks, malcolm. The way I have it now, I have the strings to be 
> substituted initialized in source code:
> 
>     const char *executable1 = "arrow";
>     const char *executable2 = "mahershala";
> 
> How would the memory considerations go if these were to come off the 
> command line with argv[]?
> 
argv[] strings are writeable, but it's a bad idea to write to them.

In all but the smallest programs, you need to read several options and (usually)
filenames from the commandline. I have an options parser which internally
duplicates argv. You then call it to get the options and filenames, and filenames
are returned as char *s allocated by malloc().

it seems very efficient - to duplicate a string twice just to pass it back up to
main, but it is safe. All the string are now in heap memory.

It's best to treat your strings as constants. If you want to change a string, create
a new one. The destroy the old one and reassign, if you want to edit the string.

 
 so
    char *exe1 = mystdup(argv[1]);


    char *pathconcat(char *first, char *second)
   
  {
      char *answer = malloc(strlen(first) + strlen(second) + 2);
      /* the allocation won't fail on a medium to large computer, if it does just quit/
     strcpy(answer, first);
     strcat(answer, "/"):
     strcpy(answer, second);
     /* we know all these are safe because we've taken the sizes of the strings */

    return answer;
  }
 
Now in fact you have several segments to build up. so.

char *pathtoexe = mystrup(exe1);
char *temp;

temp = pathconcat(part1, pathtoexe):
free(part1);
part1 = 0;
free(pathtoexex);
pathtoexe = temp; 
temp = 0;
    
it looks like a long way round, but you can put this logic into a loop, with the variable 
"pathtoexe" steadily building up to the full path, which could have an arbitrary number of
sections.

[toc] | [prev] | [next] | [standalone]


#104848

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2017-02-27 13:25 +0000
Message-ID<871suju5or.fsf@bsb.me.uk>
In reply to#104846
Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
<snip>
>     char *pathconcat(char *first, char *second)
>
>   {
>       char *answer = malloc(strlen(first) + strlen(second) + 2);
>       /* the allocation won't fail on a medium to large computer, if it does just quit/

(missing *)

>      strcpy(answer, first);
>      strcat(answer, "/"):
>      strcpy(answer, second);

I think you meant strcat here too.  I'd remember the first length and I
like to add in the extras like this:

  size_t l1 = strlen(first);
  char *name = malloc(l1 + 1 + strlen(second) + 1);
  if (name) {
     memcpy(name, first, l1);
     name[l1] = '/';
     strcpy(name + l1 + 1, second);
  }

Also, for some file names, you can use a VLA as I suggested in another
post.

<snip>
-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#104899

FromKeith Thompson <kst-u@mib.org>
Date2017-02-27 09:56 -0800
Message-ID<lnk28bfrgd.fsf@kst-u.example.com>
In reply to#104846
Malcolm McLean <malcolm.mclean5@btinternet.com> writes:
> On Monday, February 27, 2017 at 12:41:24 PM UTC, fred flintstone wrote:
>> On 02/26/2017 06:42 AM, Malcolm McLean wrote:
>> Thanks, malcolm. The way I have it now, I have the strings to be 
>> substituted initialized in source code:
>> 
>>     const char *executable1 = "arrow";
>>     const char *executable2 = "mahershala";
>> 
>> How would the memory considerations go if these were to come off the 
>> command line with argv[]?
>> 
> argv[] strings are writeable, but it's a bad idea to write to them.

I don't believe anyone suggested writing to the argument strings, nor
would there be any reason to do so here.

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

[toc] | [prev] | [next] | [standalone]


#104769

From"Mr. Man-wai Chang" <toylet.toylet@gmail.com>
Date2017-02-27 01:00 +0800
Message-ID<o8v1fh$uo7$1@dont-email.me>
In reply to#104752
On 26/02/2017 8:14 PM, fred flintstone wrote:
>
> 'arrow'
> , how do I declare this string to exist safely?

Is the length of this string static or dynamic?

> Do I malloc a 1000 because someone has to make an adult decision?

Depends on whether you wanna use the same memory space for many purposes.

-- 
   @~@   Remain silent! Drink, Blink, Stretch! Live long and prosper!!
  / v \  Simplicity is Beauty!
/( _ )\ May the Force and farces be with you!
   ^ ^   (x86_64 Ubuntu 9.10)  Linux 2.6.39.3
不借貸! 不詐騙! 不援交! 不打交! 不打劫! 不自殺! 請考慮綜援 (CSSA):
http://www.swd.gov.hk/tc/index/site_pubsvc/page_socsecu/sub_addressesa

[toc] | [prev] | [next] | [standalone]


#104797

From"James R. Kuyper" <jameskuyper@verizon.net>
Date2017-02-26 18:55 -0500
Message-ID<6b1df453-b6df-3cf8-eb6e-255c37ef241a@verizon.net>
In reply to#104752
On 02/26/2017 07:14 AM, fred flintstone wrote:
...
> So there's 3DBESNUB type things ...

Is this 
<https://www.physics.byu.edu/faculty/christensen/Physics%20121/3D%20BE%20SNUB.htm> 
what you're referring to?

> ... Right
> at the top is that I don't know how to declare strings in c in a safe way.
>
> Let's say that you're hard-coding a string between single quotes, for

If it's between single quotes, it's not a string, it's a single 
character constant. "The value of an integer character constant 
containing more than one character (e.g., 'ab'), or containing a 
character or escape sequence that does not map to a single-byte 
execution character, is implementation-defined." (6.4.4.4p10). Such 
constants are very seldom used. The fact that their value is 
implementation-defined makes them useless for portable code. I'd guess 
that most C programmers are unaware that such a construct is even 
permitted. Therefore, I doubt that it's what you actually meant. You 
probably meant double quotes, and that's what my answers farther down 
assume.

In case you're wondering what character constants containing multiple 
characters are useful for, here's some examples of what's permitted:

Two trivial possibilities are that 'arrow' == 'a', or 'arrow' == 'w'.

Note that character constants, despite their name, have values of type 
'int'. Therefore, on a system where char is unsigned, and int has more 
than 5*CHAR_BIT bits, an implementation could choose to define that

     'arrow' == (((('a'*CHAR_MAX + 'r')*CHAR_MAX + 'r')*CHAR_MAX + 'o')*
                  CHAR_MAX + 'w')

> example:
>
> 'arrow'
>
> , how do I declare this string to exist safely?

That depends upon which danger you're hoping to avoid. Define the 
danger, and we can tell you the best way to minimize it. However, don't 
expect too much. C is a very low-level language - it does very little to 
protect you from shooting yourself in the foot. It's the language used 
to efficiently implement many of the safer languages. Here's several 
different options, each of which has different advantages and disadvantages:

     #define ARROW "arrow"

     const char *parrow = "arrow";
     char arrow[] = "arrow";
     // Either of those definitions could be declared static
     // Either of those definitions could appear at either file scope or
     //    block scope.

     parrow = malloc(sizeof "arrow"));
     memcpy(parrow, "arrow", sizeof "arrow");

> Do I malloc a 1000 because someone has to make an adult decision?

That depends entirely upon what danger you're trying to protect against. 
As a general rule, if that solution helps you avoid a danger, then that 
danger involves bad coding practices. In that case, you're better off 
avoiding that danger by by improving your coding practices than by 
allocating 1000 bytes to hold a 5-character string.

[toc] | [prev] | [next] | [standalone]


#105078

Fromfred flintstone <fred@server.invalid>
Date2017-02-28 04:20 -0800
Message-ID<ehl892F1h4hU1@mid.individual.net>
In reply to#104797
On 02/26/2017 03:55 PM, James R. Kuyper wrote:
> On 02/26/2017 07:14 AM, fred flintstone wrote:
> ...
>> So there's 3DBESNUB type things ...
>
> Is this
> <https://www.physics.byu.edu/faculty/christensen/Physics%20121/3D%20BE%20SNUB.htm>
> what you're referring to?

Yeah. I'm trying to paint the pictures that I need to to make it around 
the bases on this one. Better usenet practice is when OP does not force 
readers to follow links, as these might be suspect. I'm left to paint a 
picture with words.

I want to draw the attention of respondents down here, as I announce 
myself safe on some type of first base, fulfilling D1 of the three D's. 
D1 might be a portrait of the client of the C application. The client 
is, first and foremost, me, and then everyone I take care of with the 
same methods. Many are simple pioneers, who don't need to be dished out 
to what's Out There.

>
>> ... Right
>> at the top is that I don't know how to declare strings in c in a safe
>> way.
>>
>> Let's say that you're hard-coding a string between single quotes, for
>
> If it's between single quotes, it's not a string, it's a single
> character constant. "The value of an integer character constant
> containing more than one character (e.g., 'ab'), or containing a
> character or escape sequence that does not map to a single-byte
> execution character, is implementation-defined." (6.4.4.4p10). Such
> constants are very seldom used. The fact that their value is
> implementation-defined makes them useless for portable code. I'd guess
> that most C programmers are unaware that such a construct is even
> permitted. Therefore, I doubt that it's what you actually meant. You
> probably meant double quotes, and that's what my answers farther down
> assume.
>
> In case you're wondering what character constants containing multiple
> characters are useful for, here's some examples of what's permitted:
>
> Two trivial possibilities are that 'arrow' == 'a', or 'arrow' == 'w'.
>
> Note that character constants, despite their name, have values of type
> 'int'. Therefore, on a system where char is unsigned, and int has more
> than 5*CHAR_BIT bits, an implementation could choose to define that
>
>     'arrow' == (((('a'*CHAR_MAX + 'r')*CHAR_MAX + 'r')*CHAR_MAX + 'o')*
>                  CHAR_MAX + 'w')
>

Thank you for comment which brought me off single quotes.
>> example:
>>
>> 'arrow'
>>
>> , how do I declare this string to exist safely?
>
> That depends upon which danger you're hoping to avoid. Define the
> danger, and we can tell you the best way to minimize it. However, don't
> expect too much. C is a very low-level language - it does very little to
> protect you from shooting yourself in the foot. It's the language used
> to efficiently implement many of the safer languages. Here's several
> different options, each of which has different advantages and
> disadvantages:
>
>     #define ARROW "arrow"
>
>     const char *parrow = "arrow";
>     char arrow[] = "arrow";
>     // Either of those definitions could be declared static
>     // Either of those definitions could appear at either file scope or
>     //    block scope.
>
>     parrow = malloc(sizeof "arrow"));
>     memcpy(parrow, "arrow", sizeof "arrow");
>

Listen to me james. Have you ever used 'malloc' as a verb? If you have a 
declaration like:

const char *parrow = "arrow";

, can one say that it has been malloced, or is it only correct to use 
the grown-up term of "allocated?" (Might there be a malloc right under 
the patina?)
>> Do I malloc a 1000 because someone has to make an adult decision?
>
> That depends entirely upon what danger you're trying to protect against.
> As a general rule, if that solution helps you avoid a danger, then that
> danger involves bad coding practices. In that case, you're better off
> avoiding that danger by by improving your coding practices than by
> allocating 1000 bytes to hold a 5-character string.

This source considers some minimal cases. I like to write quines. 
Douglas Hofstadter's Goedel Escher Bach set me back 44 marks, a lot of 
money to me.

Anyways, the idea is that the source is reproduced faithfully. I'm not 
doing it in a strict mathematical sense (yet). I'll begin with a source 
listing of the driving .sh, avec warnings, the output thereof, and then 
ask questions. So, tja:

$ sh toolchain2.sh
sub1.c: In function ‘main’:
sub1.c:13:15: warning: unused variable ‘ext’ [-Wunused-variable]
    const char *ext = "sh";
                ^
sub1.c:12:15: warning: unused variable ‘base’ [-Wunused-variable]
    const char *base = "toolchain";
                ^
sub1.c:11:15: warning: unused variable ‘executable2’ [-Wunused-variable]
    const char *executable2 = "mahershala";
                ^
sub1.c:10:15: warning: unused variable ‘executable1’ [-Wunused-variable]
    const char *executable1 = "arrow";
                ^
sub1.c:8:7: warning: unused variable ‘version’ [-Wunused-variable]
    int version, c, i;
        ^
$ pwd
/home/bob/Documents/programming/Book Examples/ch02/command_line
$ ls -l
total 44
-rw-rw-r-- 1 bob bob 1804 Feb 26 01:03 arrow.c
-rw-rw-r-- 1 bob bob 1008 Feb 27 17:42 awk3
-rwxrwxr-x 1 bob bob 9104 Feb 27 18:25 sub1
-rw-rw-r-- 1 bob bob  950 Feb 27 18:24 sub1.c
-rw-rw-r-- 1 bob bob 1030 Feb 27 18:15 sub1.c~
-rw-rw-r-- 1 bob bob  969 Feb 27 18:25 text1.txt
-rw-rw-r-- 1 bob bob  103 Feb 27 18:22 toolchain2.sh
-rwxrwxr-x 1 bob bob  273 Feb 26 01:51 toolchain3.sh
-rw-rw-r-- 1 bob bob  273 Feb 27 18:25 toolchain4.sh
$ cat toolchain2.sh
gcc -Wall -Wextra -o sub1 sub1.c >text1.txt
./sub1 arrow mahershala >>text1.txt
cat sub1.c >>text1.txt
$ cat text1.txt
3
arrow
mahershala
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main (int argc, char *argv[])
{
   int version, c, i;
   FILE *fptr, *gptr;
   const char *executable1 = "arrow";
   const char *executable2 = "mahershala";
   const char *base = "toolchain";
   const char *ext = "sh";



   printf ("%d\n", argc);
   for (i = 1; i < argc; i++) {
     printf ("%s\n", argv[i]);
   }
   fptr = fopen ("toolchain3.sh", "r");
   if (fptr == NULL) {
     printf ("fopen no bueno");
     exit (1);
   }
   gptr = fopen ("toolchain4.sh", "w");

   if (gptr == NULL) {
     printf ("gopen no bueno");
     exit (1);
   }

   while (1) {
     c = fgetc (fptr);

     if (c == EOF)
       break;
     else
       putc (c, gptr);
   }


   fclose (fptr);
   fclose (gptr);

   return 0;
}

char *
mystdrdup (const char *str)
{
   size_t len = strlen (str);
   char *answer = malloc (len + 1);
   if (answer)
     strcpy (answer, str);
   else {			/* error handling here */
   };

   return answer;
}
$

Q1) Is this standard, portable, contemporary C?

Q2) This program shall be legal C. What constraints does that put on the 
cumulative size on what comes from argv?

The specification of this program will handle the case that what is 
passed to it exceeds the allowable parameters. Is it INT_MIN?

Q3) I have Plauger's _Standard C Library_ under my bed somewhere. How 
would the list of necessary .h files differ from then to contemporary C?

Thank you for your comment, and remember, some people warm up to a topic....
-- 
fred flintstone

[toc] | [prev] | [next] | [standalone]


#105097

FromDavid Brown <david.brown@hesbynett.no>
Date2017-02-28 14:38 +0100
Message-ID<o93ucu$3nv$1@dont-email.me>
In reply to#105078
On 28/02/17 13:20, fred flintstone wrote:
> On 02/26/2017 03:55 PM, James R. Kuyper wrote:
>> On 02/26/2017 07:14 AM, fred flintstone wrote:
>> ...
>>> So there's 3DBESNUB type things ...
>>
>> Is this
>> <https://www.physics.byu.edu/faculty/christensen/Physics%20121/3D%20BE%20SNUB.htm>
>>
>> what you're referring to?
> 
> Yeah. I'm trying to paint the pictures that I need to to make it around
> the bases on this one. Better usenet practice is when OP does not force
> readers to follow links, as these might be suspect. I'm left to paint a
> picture with words.

It is even better Usenet practice to explain what is relevant, in clear
terms appropriate to the group.  Stop "painting pictures" and using
silly American sporting terms ("make it around the bases").  Just use
plain English.  And while posting links is often bad, it is far worse to
use local acronyms such as your 3D-thingy that are meaningless to almost
everyone unless they spent time researching them.

> 
> I want to draw the attention of respondents down here, as I announce
> myself safe on some type of first base, fulfilling D1 of the three D's.
> D1 might be a portrait of the client of the C application. The client
> is, first and foremost, me, and then everyone I take care of with the
> same methods. Many are simple pioneers, who don't need to be dished out
> to what's Out There.

The words may be spelt correctly, but you are writing gibberish.  Please
stop.  You will end up on killfiles or being ignored - and the people
who killfile you are mostly the people (like Richard Heathfield, who has
also warned you) who give good, solid answers in this group.

<snip>

>>>
>>> , how do I declare this string to exist safely?
>>
>> That depends upon which danger you're hoping to avoid. Define the
>> danger, and we can tell you the best way to minimize it. However, don't
>> expect too much. C is a very low-level language - it does very little to
>> protect you from shooting yourself in the foot. It's the language used
>> to efficiently implement many of the safer languages. Here's several
>> different options, each of which has different advantages and
>> disadvantages:
>>
>>     #define ARROW "arrow"
>>
>>     const char *parrow = "arrow";
>>     char arrow[] = "arrow";
>>     // Either of those definitions could be declared static
>>     // Either of those definitions could appear at either file scope or
>>     //    block scope.
>>
>>     parrow = malloc(sizeof "arrow"));
>>     memcpy(parrow, "arrow", sizeof "arrow");
>>
> 
> Listen to me james. Have you ever used 'malloc' as a verb? If you have a
> declaration like:
> 
> const char *parrow = "arrow";
> 
> , can one say that it has been malloced, or is it only correct to use
> the grown-up term of "allocated?" (Might there be a malloc right under
> the patina?)

Some people use malloc as a verb, others would say allocated on the heap
or dynamically allocated.  No one would say that about "parrow" or
"arrow" above, because there has been no dynamic allocation.

>>> Do I malloc a 1000 because someone has to make an adult decision?
>>
>> That depends entirely upon what danger you're trying to protect against.
>> As a general rule, if that solution helps you avoid a danger, then that
>> danger involves bad coding practices. In that case, you're better off
>> avoiding that danger by by improving your coding practices than by
>> allocating 1000 bytes to hold a 5-character string.
> 
> This source considers some minimal cases. I like to write quines.
> Douglas Hofstadter's Goedel Escher Bach set me back 44 marks, a lot of
> money to me.

More meaningless gibberish.

> 
> Anyways, the idea is that the source is reproduced faithfully. I'm not
> doing it in a strict mathematical sense (yet). I'll begin with a source
> listing of the driving .sh, avec warnings, the output thereof, and then
> ask questions. So, tja:
> 
> $ sh toolchain2.sh
> sub1.c: In function ‘main’:
> sub1.c:13:15: warning: unused variable ‘ext’ [-Wunused-variable]
>    const char *ext = "sh";
>                ^
> sub1.c:12:15: warning: unused variable ‘base’ [-Wunused-variable]
>    const char *base = "toolchain";
>                ^
> sub1.c:11:15: warning: unused variable ‘executable2’ [-Wunused-variable]
>    const char *executable2 = "mahershala";
>                ^
> sub1.c:10:15: warning: unused variable ‘executable1’ [-Wunused-variable]
>    const char *executable1 = "arrow";
>                ^
> sub1.c:8:7: warning: unused variable ‘version’ [-Wunused-variable]
>    int version, c, i;
>        ^
> $ pwd
> /home/bob/Documents/programming/Book Examples/ch02/command_line
> $ ls -l
> total 44
> -rw-rw-r-- 1 bob bob 1804 Feb 26 01:03 arrow.c
> -rw-rw-r-- 1 bob bob 1008 Feb 27 17:42 awk3
> -rwxrwxr-x 1 bob bob 9104 Feb 27 18:25 sub1
> -rw-rw-r-- 1 bob bob  950 Feb 27 18:24 sub1.c
> -rw-rw-r-- 1 bob bob 1030 Feb 27 18:15 sub1.c~
> -rw-rw-r-- 1 bob bob  969 Feb 27 18:25 text1.txt
> -rw-rw-r-- 1 bob bob  103 Feb 27 18:22 toolchain2.sh
> -rwxrwxr-x 1 bob bob  273 Feb 26 01:51 toolchain3.sh
> -rw-rw-r-- 1 bob bob  273 Feb 27 18:25 toolchain4.sh
> $ cat toolchain2.sh
> gcc -Wall -Wextra -o sub1 sub1.c >text1.txt

You should add "-O1" to that list - it lets gcc do better analysis for
more warnings.

> ./sub1 arrow mahershala >>text1.txt
> cat sub1.c >>text1.txt
> $ cat text1.txt
> 3
> arrow
> mahershala
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> 
> int
> main (int argc, char *argv[])
> {
>   int version, c, i;
>   FILE *fptr, *gptr;
>   const char *executable1 = "arrow";
>   const char *executable2 = "mahershala";
>   const char *base = "toolchain";
>   const char *ext = "sh";
> 
> 
> 
>   printf ("%d\n", argc);
>   for (i = 1; i < argc; i++) {
>     printf ("%s\n", argv[i]);
>   }
>   fptr = fopen ("toolchain3.sh", "r");
>   if (fptr == NULL) {
>     printf ("fopen no bueno");
>     exit (1);
>   }
>   gptr = fopen ("toolchain4.sh", "w");
> 
>   if (gptr == NULL) {
>     printf ("gopen no bueno");
>     exit (1);
>   }
> 
>   while (1) {
>     c = fgetc (fptr);
> 
>     if (c == EOF)
>       break;
>     else
>       putc (c, gptr);
>   }
> 
> 
>   fclose (fptr);
>   fclose (gptr);
> 
>   return 0;
> }
> 

Please remove Malcolm's useless "mytstdrdup" function from your code.
His post was not helpful in any way.

> char *
> mystdrdup (const char *str)
> {
>   size_t len = strlen (str);
>   char *answer = malloc (len + 1);
>   if (answer)
>     strcpy (answer, str);
>   else {            /* error handling here */
>   };
> 
>   return answer;
> }
> $
> 
> Q1) Is this standard, portable, contemporary C?

You have already been given a number of suggestions to improve the code,
including solving your original problem.

> 
> Q2) This program shall be legal C. What constraints does that put on the
> cumulative size on what comes from argv?

It is up to the implementation to decide what comes in on argv.

> 
> The specification of this program will handle the case that what is
> passed to it exceeds the allowable parameters. Is it INT_MIN?

You are not currently using anything that is passed to the program, and
we have no way of guessing what that might be, or what your
specifications are.

> 
> Q3) I have Plauger's _Standard C Library_ under my bed somewhere. How
> would the list of necessary .h files differ from then to contemporary C?

I don't know that book.  There are plenty of references for modern
standard C headers.  The ultimate reference is the C standards - N1570
is a freely available draft of C11.  But the standards documents are not
easily going for a beginner.  I would recommend this site:

<http://en.cppreference.com/w/c/header>

The C FAQ at <http://c-faq.com/> is also an excellent reference.

> 
> Thank you for your comment, and remember, some people warm up to a
> topic....

[toc] | [prev] | [next] | [standalone]


#105106

FromKeith Thompson <kst-u@mib.org>
Date2017-02-28 08:33 -0800
Message-ID<lno9xme0md.fsf@kst-u.example.com>
In reply to#105097
David Brown <david.brown@hesbynett.no> writes:
> On 28/02/17 13:20, fred flintstone wrote:
[...]
>> gcc -Wall -Wextra -o sub1 sub1.c >text1.txt
>
> You should add "-O1" to that list - it lets gcc do better analysis for
> more warnings.

Why do you recommend -O1 rather than -O3?

If you want to write standard C, I'd also recommend
    -std=c11 -pedantic-errors

If you use -pedantic rather than -pedantic-errors, some errors will be
diagnosed with non-fatal warnings; that's ok if you treat warnings
*very* seriously.

[...]

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

[toc] | [prev] | [next] | [standalone]


Page 4 of 5 — ← Prev page 1 2 3 [4] 5  Next page →

Back to top | Article view | comp.lang.c


csiph-web