a few doubts!

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • maadhuu

    a few doubts!

    #include<stdio. h>
    #include<conio. h>
    #include<string .h>
    main()
    {
    char * a= "bcd";
    clrscr();
    strcpy(a,"hello ");
    a = "fgh";
    a[0] = 't';
    printf("%s",a);
    }


    now, in TC there is absolutely no error .....i thought it
    should........c oz' when i declare a as a char * and assign it to some
    string then it should be a constant and cannot do things like a[0] = '4'
    and stuff........in fact the entire thing here works properly....so why
    should it work properly??


  • Lew Pitcher

    #2
    Re: a few doubts!

    -----BEGIN PGP SIGNED MESSAGE-----
    Hash: SHA1

    maadhuu wrote:[color=blue]
    > #include<stdio. h>
    > #include<conio. h>[/color]

    conio.h is not a standard header. It's contents could be anything, and could
    affect your program in ways we cannot determine

    [color=blue]
    > #include<string .h>
    > main()[/color]

    main() takes either two arguments or none, and returns an int
    you should use one of the two legal variants here, likely
    int main(void)
    [color=blue]
    > {
    > char * a= "bcd";[/color]

    a is declared as a pointer to an array of 4 char.
    a can be altered
    the array of 4 char cannot be altered
    [color=blue]
    > clrscr();[/color]

    clrscr() is not a standard function. It's actions and side-effects could do
    anything, and will affect your program in ways we cannot determine.
    [color=blue]
    > strcpy(a,"hello ");[/color]

    At least, undefined behaviour, because *a is only 4 char long, and the
    side-effect (and function) of strcpy() would be to overwrite that space with a
    6 char long value. 6 chars don't fit into a 4 char space.

    The more knowledgable ones around here will tell you whether this is "illegal
    behaviour" (because of the side-effect of strcpy(), which would be to attempt
    to overwrite a char constant) or just "undefined behaviour".

    [color=blue]
    > a = "fgh";[/color]

    Legal. You are not replacing the constant char array, you are replacing the
    variable pointer.
    [color=blue]
    > a[0] = 't';[/color]

    IIUC, this should be illegal.
    [color=blue]
    > printf("%s",a);[/color]

    main() returns an int. return one here.
    (Unless, your compiler is C99 compliant, in which case, the return value is
    optional and defaults to a pre-determined value).
    [color=blue]
    > }
    >
    >
    > now, in TC there is absolutely no error .....i thought it
    > should........c oz' when i declare a as a char * and assign it to some
    > string then it should be a constant and cannot do things like a[0] = '4'
    > and stuff........in fact the entire thing here works properly....so why
    > should it work properly??[/color]


    The compiler is non-compliant?
    The compiler is broken?


    - --
    Lew Pitcher

    Master Codewright & JOAT-in-training | GPG public key available on request
    Registered Linux User #112576 (http://counter.li.org/)
    Slackware - Because I know what I'm doing.
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v1.2.4 (GNU/Linux)

    iD8DBQFCc5PDagV FX4UWr64RAs8TAJ 4p+ZyxVWzyLHSgh tGc9yAdO9altQCg kxAZ
    TDeV/fVJ3HZ6ZPh/iGDjvb8=
    =jTH7
    -----END PGP SIGNATURE-----

    Comment

    • osmium

      #3
      Re: a few doubts!

      "maadhuu" writes:
      [color=blue]
      > #include<stdio. h>
      > #include<conio. h>
      > #include<string .h>
      > main()
      > {
      > char * a= "bcd";
      > clrscr();
      > strcpy(a,"hello ");
      > a = "fgh";
      > a[0] = 't';
      > printf("%s",a);
      > }
      >
      >
      > now, in TC there is absolutely no error .....i thought it
      > should........c oz' when i declare a as a char * and assign it to some
      > string then it should be a constant and cannot do things like a[0] = '4'
      > and stuff........in fact the entire thing here works properly....so why
      > should it work properly??[/color]

      It would certainly be nicer if this didn't work, but I am not surprised that
      it does. Only a language lawyer can determine whether your compiler breaks
      some mandated rule, as opposed to simply letting some sloppy code through.

      The fact that the strcpy works is especially troubling. I think part of the
      venom against Schildt and his books is that he actually used to write
      similar code on purpose. Probably not the strcpy with the too big aspect,
      though.

      FWIW it fails on DevC (mingw) and I would expect it to fail on most, if not
      all, modern compilers. .


      Comment

      • Flash Gordon

        #4
        Re: a few doubts!

        maadhuu wrote:[color=blue]
        > #include<stdio. h>
        > #include<conio. h>
        > #include<string .h>
        > main()
        > {
        > char * a= "bcd";
        > clrscr();
        > strcpy(a,"hello ");
        > a = "fgh";
        > a[0] = 't';
        > printf("%s",a);
        > }
        >
        > now, in TC there is absolutely no error .....i thought it
        > should........c oz' when i declare a as a char * and assign it to some
        > string then it should be a constant and cannot do things like a[0] = '4'
        > and stuff........in fact the entire thing here works properly....so why
        > should it work properly??[/color]

        It worked properly because it was neither an important demo with a large
        sale hanging off it nor you showing it to your boss.

        The standard says you are not allowed to write to a string literal, it
        does not say it will generate an error or crash if you do.
        --
        Flash Gordon
        Living in interesting times.
        Although my email address says spam, it is real and I read it.

        Comment

        • Mark McIntyre

          #5
          Re: a few doubts!

          On Sat, 30 Apr 2005 10:18:43 -0400, in comp.lang.c , Lew Pitcher
          <lpitcher@sympa tico.ca> wrote:
          [color=blue][color=green]
          >> char * a= "bcd";[/color][/color]
          [color=blue]
          >the array of 4 char cannot be altered[/color]

          yes
          [color=blue][color=green]
          >> strcpy(a,"hello ");[/color][/color]

          so this is undefined behaviour.
          [color=blue]
          >The more knowledgable ones around here will tell you whether this is "illegal
          >behaviour" (because of the side-effect of strcpy(), which would be to attempt
          >to overwrite a char constant) or just "undefined behaviour".[/color]

          It is undefined. There's no syntax error here, so no reason to abort
          compilation, if thats what you mean by 'illegal'.
          [color=blue][color=green]
          >> a[0] = 't';[/color]
          >
          >IIUC, this should be illegal.[/color]

          Its undefined behaviour.
          [color=blue]
          >The compiler is non-compliant?[/color]

          the warning levels are too low?
          [color=blue]
          >The compiler is broken?[/color]

          The compiler is operating perfectly, but isn't obligated to produce a
          diagnostic for careless programming.

          --
          Mark McIntyre
          CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
          CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt >

          ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
          http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
          ----= East and West-Coast Server Farms - Total Privacy via Encryption =----

          Comment

          • Emmanuel Delahaye

            #6
            Re: a few doubts!

            maadhuu wrote on 30/04/05 :[color=blue]
            > #include<stdio. h>
            > #include<conio. h>
            > #include<string .h>
            > main()
            > {
            > char * a= "bcd";
            > clrscr();
            > strcpy(a,"hello ");
            > a = "fgh";
            > a[0] = 't';
            > printf("%s",a);
            > }[/color]

            Crashy!

            Get a better compiler an tunigs...

            main.c:17: warning: return type defaults to `int'
            main.c:17: warning: function declaration isn't a prototype
            main.c: In function `main':
            main.c:18: warning: initialization discards qualifiers from pointer
            target type
            main.c:21: warning: assignment discards qualifiers from pointer target
            type main.c:24: warning: control reaches end of non-void function

            --
            Emmanuel
            The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
            The C-library: http://www.dinkumware.com/refxc.html

            "C is a sharp tool"

            Comment

            • maadhuu

              #7
              Re: a few doubts!

              well, there is a 3rd way to pass arguments in main,which is environment
              variables.....s ince u said there are only 2 or none.......
              and i don't think this compiler is C-99 compliant.

              Comment

              • Emmanuel Delahaye

                #8
                Re: a few doubts!

                (supersedes <mn.f4557d54dfe 1cbc0.15512@YOU RBRAnoos.fr>)

                maadhuu wrote on 30/04/05 :[color=blue]
                > #include<stdio. h>
                > #include<conio. h>
                > #include<string .h>
                > main()
                > {
                > char * a= "bcd";
                > clrscr();
                > strcpy(a,"hello ");
                > a = "fgh";
                > a[0] = 't';
                > printf("%s",a);
                > }[/color]

                Crashy!

                Get a better compiler and tunings...

                main.c:17: warning: return type defaults to `int'
                main.c:17: warning: function declaration isn't a prototype
                main.c: In function `main':
                main.c:18: warning: initialization discards qualifiers from pointer
                target type
                main.c:21: warning: assignment discards qualifiers from pointer target
                type main.c:24: warning: control reaches end of non-void function

                --
                Emmanuel
                The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
                The C-library: http://www.dinkumware.com/refxc.html

                "Clearly your code does not meet the original spec."
                "You are sentenced to 30 lashes with a wet noodle."
                -- Jerry Coffin in a.l.c.c++

                Comment

                • Walter Roberson

                  #9
                  Re: a few doubts!

                  In article <ba25d2f5e88c05 dac99eb6cc9120d 14f@localhost.t alkaboutprogram ming.com>,
                  maadhuu <madhu_ranjan_m @yahoo.com> wrote:[color=blue]
                  >well, there is a 3rd way to pass arguments in main,which is environment
                  >variables..... since u said there are only 2 or none.......[/color]

                  Passing an environment variable to main is a platform-specific
                  extension. The only *portable* choices are 2 arguments or no arguments.
                  --
                  "I want to make sure [a user] can't get through ... an online
                  experience without hitting a Microsoft ad"
                  -- Steve Ballmer [Microsoft Chief Executive]

                  Comment

                  • Emmanuel Delahaye

                    #10
                    Re: a few doubts!

                    Lew Pitcher wrote on 30/04/05 :[color=blue][color=green]
                    >> <...> infact the entire thing here works properly....so why
                    >> should it work properly??[/color]
                    >
                    > The compiler is non-compliant?
                    > The compiler is broken?[/color]

                    None of this. The compiler is correct (KIM that the warnings are
                    optional) and the behaviour is undefined. The OP is unlucky because the
                    program don't crash.

                    --
                    Emmanuel
                    The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
                    The C-library: http://www.dinkumware.com/refxc.html

                    ..sig under repair

                    Comment

                    • Emmanuel Delahaye

                      #11
                      Re: a few doubts!

                      (supersedes <mn.f4697d54b61 47e54.15512@YOU RBRAnoos.fr>)

                      Lew Pitcher wrote on 30/04/05 :[color=blue][color=green]
                      >> <...> infact the entire thing here works properly....so why
                      >> should it work properly??[/color]
                      >
                      > The compiler is non-compliant?
                      > The compiler is broken?[/color]

                      None of this. The compiler is correct (KIM that the warnings are
                      optional) and the behaviour is undefined. The OP is unlucky because the
                      program doesn't crash.

                      --
                      Emmanuel
                      The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
                      The C-library: http://www.dinkumware.com/refxc.html

                      "Clearly your code does not meet the original spec."
                      "You are sentenced to 30 lashes with a wet noodle."
                      -- Jerry Coffin in a.l.c.c++

                      Comment

                      • Emmanuel Delahaye

                        #12
                        Re: a few doubts!

                        Flash Gordon wrote on 30/04/05 :[color=blue]
                        > It worked properly because it was neither an important demo with a large sale
                        > hanging off it nor you showing it to your boss.[/color]

                        He he ! Murphy's rules...
                        [color=blue]
                        > The standard says you are not allowed to write to a string literal, it does
                        > not say it will generate an error or crash if you do.[/color]

                        --
                        Emmanuel
                        The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
                        The C-library: http://www.dinkumware.com/refxc.html

                        ..sig under repair

                        Comment

                        • SM Ryan

                          #13
                          Re: a few doubts!

                          "maadhuu" <madhu_ranjan_m @yahoo.com> wrote:
                          # #include<stdio. h>
                          # #include<conio. h>
                          # #include<string .h>
                          # main()
                          # {
                          # char * a= "bcd";
                          # clrscr();
                          # strcpy(a,"hello ");
                          # a = "fgh";
                          # a[0] = 't';
                          # printf("%s",a);
                          # }

                          Some compilers allow strings to be overwritten by placing them in read-write memory
                          sometimes with the expectation the string can be modified. Writing outside an array
                          bounds does not necessarily trigger a fault action.

                          The code results are machine and compiler dependent.

                          --
                          SM Ryan http://www.rawbw.com/~wyrmwif/
                          I think that's kinda of personal; I don't think I should answer that.

                          Comment

                          • Keith Thompson

                            #14
                            Re: a few doubts!

                            SM Ryan <wyrmwif@tang o-sierra-oscar-foxtrot-tango.fake.org> writes:[color=blue]
                            > "maadhuu" <madhu_ranjan_m @yahoo.com> wrote:[color=green]
                            > > #include<stdio. h>
                            > > #include<conio. h>
                            > > #include<string .h>
                            > > main()
                            > > {
                            > > char * a= "bcd";
                            > > clrscr();
                            > > strcpy(a,"hello ");
                            > > a = "fgh";
                            > > a[0] = 't';
                            > > printf("%s",a);
                            > > }[/color]
                            >
                            > Some compilers allow strings to be overwritten by placing them in
                            > read-write memory sometimes with the expectation the string can be
                            > modified. Writing outside an array bounds does not necessarily
                            > trigger a fault action.
                            >
                            > The code results are machine and compiler dependent.[/color]

                            [ Non-traditional '#' quoting character changed to '>'. ]
                            [ Excessively long lines reformatted. ]
                            [ Becoming seriously annoyed by gratuitously non-traditional formatting. ]

                            To be precise, an attempt to modify a string literal invokes undefined
                            behavior. An implementation is allowed to place string literals in a
                            read-only memory segment, causing a trap whenever the program attempts
                            to write to them. It's also allowed to place them in read-write
                            memory, and even to share the same memory for different occurrences of
                            the same string. For example, this:

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

                            int main(void)
                            {
                            char *s = "hello, world\n";
                            strcpy(s, "HAHA!\n");
                            printf("hello, world\n");
                            return 0;
                            }

                            could legally do any of the following:

                            Blow up on the strcpy() call (perhaps with a segmentation fault).
                            Print "hello, world".
                            Print "HAHA!".
                            Print "You have invoked undefined behavior and your mother wears army boots."
                            Make demons fly out your nose.

                            Some compilers may have an an option to control whether string
                            literals are stored in read-only or read-write memory. Such an option
                            is useful mostly to diagnose this kind of problem (or, if you're
                            desparate, to work around it). The only real solution is to avoid
                            writing to string literals in the first place.

                            One oddity is that, for historical reasons, a string literal is not
                            treated as "const". If it were, the compiler would be required to
                            diagnose most cases of this error.

                            --
                            Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                            San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                            We must do something. This is something. Therefore, we must do this.

                            Comment

                            • Walter Roberson

                              #15
                              Re: a few doubts!

                              In article <ln1x8sc9tk.fsf @nuthaus.mib.or g>,
                              Keith Thompson <kst-u@mib.org> wrote:[color=blue]
                              >To be precise, an attempt to modify a string literal invokes undefined
                              >behavior.[/color]
                              [color=blue]
                              >For example, this:[/color]
                              [color=blue]
                              >could legally do any of the following:[/color]
                              [color=blue]
                              >Blow up on the strcpy() call (perhaps with a segmentation fault).[/color]
                              [color=blue]
                              >Make demons fly out your nose.[/color]
                              [color=blue]
                              >Some compilers may have an an option to control whether string
                              >literals are stored in read-only or read-write memory.[/color]

                              When is gcc getting a --no-nosedemons option ?
                              --
                              Feep if you love VT-52's.

                              Comment

                              Working...