doubt on char *

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

    doubt on char *

    int myfun(char *sourcebuf)
    {
    char *destbuf;
    char ch;
    while (*sourcebuf != '\0')
    {
    *destbuf++=*sou rcebuf++; --crashed here
    };
    return 1;
    }

    Can any one explain why it is crashed?
    Thankyou...
  • Eric Sosman

    #2
    Re: doubt on char *

    Fastro wrote:
    int myfun(char *sourcebuf)
    {
    char *destbuf;
    char ch;
    while (*sourcebuf != '\0')
    {
    *destbuf++=*sou rcebuf++; --crashed here
    };
    return 1;
    }
    >
    Can any one explain why it is crashed?
    Thankyou...
    It may not look like it, but this is Question 7.1 in
    the comp.lang.c Frequently Asked Questions (FAQ) list at
    <http://www.c-faq.com/>.

    --
    Eric.Sosman@sun .com

    Comment

    • Kenny McCormack

      #3
      Re: doubt on char *

      In article <9276334d-4bc0-4255-bfe6-7b8b718d1ae7@y2 2g2000prd.googl egroups.com>,
      Fastro <lencastro@gmai l.comwrote:
      >int myfun(char *sourcebuf)
      >{
      > char *destbuf;
      > char ch;
      > while (*sourcebuf != '\0')
      > {
      > *destbuf++=*sou rcebuf++; --crashed here
      > };
      > return 1;
      >}
      >
      >Can any one explain why it is crashed?
      >Thankyou...
      It may be a bug in your editing software.

      When you wrote:

      int myfun(char *sourcebuf, char *destbuf)

      It came out as:

      int myfun(char *sourcebuf)
      {
      char *destbuf;

      And, unfortunately, the compiler couldn't fix this by itself.

      Comment

      • CBFalconer

        #4
        Re: doubt on char *

        Fastro wrote: ** code edited slightly **
        >
        int myfun(char *sourcebuf) {
        char *destbuf;
        char ch;
        while (*sourcebuf != '\0') {
        *destbuf++=*sou rcebuf++; --crashed here
        };
        return 1;
        }
        >
        Can any one explain why it is crashed?
        Yes. destbuf is uninitialized. It doesn't point to any storage.

        --
        [mail]: Chuck F (cbfalconer at maineline dot net)
        [page]: <http://cbfalconer.home .att.net>
        Try the download section.

        ** Posted from http://www.teranews.com **

        Comment

        • rahul

          #5
          Re: doubt on char *

          On Jun 9, 9:06 pm, gaze...@xmissio n.xmission.com (Kenny McCormack)
          wrote:
          In article <9276334d-4bc0-4255-bfe6-7b8b718d1...@y2 2g2000prd.googl egroups.com>,
          >
          Fastro <lencas...@gmai l.comwrote:
          int myfun(char *sourcebuf)
          {
          char *destbuf;
          char ch;
          while (*sourcebuf != '\0')
          {
          *destbuf++=*sou rcebuf++; --crashed here
          };
          return 1;
          }
          >
          Can any one explain why it is crashed?
          Thankyou...
          >
          It may be a bug in your editing software.
          >
          When you wrote:
          >
          int myfun(char *sourcebuf, char *destbuf)
          >
          It came out as:
          >
          int myfun(char *sourcebuf)
          {
          char *destbuf;
          >
          And, unfortunately, the compiler couldn't fix this by itself.
          Its either this or Fastro really forgot to assign memory to destbuf
          and dereferenced god knows what.

          Comment

          • rams

            #6
            Re: doubt on char *

            On Jun 10, 9:32 am, rahul <rahulsin...@gm ail.comwrote:
            On Jun 9, 9:06 pm, gaze...@xmissio n.xmission.com (Kenny McCormack)
            wrote:
            >
            >
            >
            In article <9276334d-4bc0-4255-bfe6-7b8b718d1...@y2 2g2000prd.googl egroups.com>,
            >
            Fastro  <lencas...@gmai l.comwrote:
            >int myfun(char *sourcebuf)
            >{
               char *destbuf;
               char ch;
               while (*sourcebuf != '\0')
               {
               *destbuf++=*sou rcebuf++; --crashed here
               };
               return 1;
            >}
            >
            >Can any one explain why it is crashed?
            >Thankyou...
            >
            It may be a bug in your editing software.
            >
            When you wrote:
            >
            int myfun(char *sourcebuf, char *destbuf)
            >
            It came out as:
            >
            int myfun(char *sourcebuf)
            {
                    char *destbuf;
            >
            And, unfortunately, the compiler couldn't fix this by itself.
            >
            Its either this or Fastro really forgot to assign memory to destbuf
            and dereferenced god knows what.
            yes ,allocate memory for destbuf using malloc() &strlen()
            like destbuf=(char *)malloc(1+ strlen(sourcebu f)*sizeof(char) );
            and finally after coming out of while loop make sure to NULL the last
            character of destbuf
            i.e .., *destbuf='\0';
            and at last don't forget to free the memory

            Comment

            • santosh

              #7
              Re: doubt on char *

              rahul wrote:
              On Jun 9, 9:06 pm, gaze...@xmissio n.xmission.com (Kenny McCormack)
              wrote:
              >In article
              ><9276334d-4bc0-4255-bfe6-7b8b718d1...@y2 2g2000prd.googl egroups.com>,
              >>
              >Fastro <lencas...@gmai l.comwrote:
              >int myfun(char *sourcebuf)
              >{
              char *destbuf;
              char ch;
              while (*sourcebuf != '\0')
              {
              *destbuf++=*sou rcebuf++; --crashed here
              };
              return 1;
              >}
              >>
              >Can any one explain why it is crashed?
              >Thankyou...
              >>
              >It may be a bug in your editing software.
              >>
              >When you wrote:
              >>
              >int myfun(char *sourcebuf, char *destbuf)
              >>
              >It came out as:
              >>
              >int myfun(char *sourcebuf)
              >{
              > char *destbuf;
              >>
              >And, unfortunately, the compiler couldn't fix this by itself.
              >
              Its either this or Fastro really forgot to assign memory to destbuf
              and dereferenced god knows what.
              Er, Kenny was being his usual sarcastic self. It's extremely unlikely to
              be a bug in the editor. It's more likely a bug in the OP. :-)

              Comment

              • Chris Dollin

                #8
                Re: doubt on char *

                rams wrote:
                yes ,allocate memory for destbuf using malloc() &strlen()
                like destbuf=(char *)malloc(1+ strlen(sourcebu f)*sizeof(char) );
                (a) there's no need to, and good reasons for not, cast the `malloc`
                result to `char*`.

                (b) `sizeof char` is 1 by definition.

                char *destbuf = malloc( 1 + strlen( sourcebuf ) );

                is, I think, clearer and safer. (I'd write `+ 1` rather than `1 +`,
                but I can see the point of marking the one-more-than in this way.)

                --
                "Shopping." /Barrayar/

                Hewlett-Packard Limited registered no:
                registered office: Cain Road, Bracknell, Berks RG12 1HN 690597 England

                Comment

                • Joachim Schmitz

                  #9
                  Re: doubt on char *

                  CBFalconer wrote:
                  Fastro wrote: ** code edited slightly **
                  >>
                  >int myfun(char *sourcebuf) {
                  > char *destbuf;
                  > char ch;
                  > while (*sourcebuf != '\0') {
                  > *destbuf++=*sou rcebuf++; --crashed here
                  > };
                  > return 1;
                  >}
                  >>
                  >Can any one explain why it is crashed?
                  >
                  Yes. destbuf is uninitialized. It doesn't point to any storage.
                  A step further: because it is uninitialized, it'll contain some garbage
                  value, that, if interpreted as a pointer, will try to access some random
                  memory location. If you're lucky, you don't own that and the OS will carsh
                  the program, if you're unlucky, you'll own it and accessing it will corrupt
                  some data structuturs and you'll only notice the harm it did much later and
                  have major difficulties to find were it went wrong.
                  So be hapy it crashed on you right away...

                  Bye, Jojo


                  Comment

                  • Richard

                    #10
                    Re: doubt on char *

                    "Joachim Schmitz" <nospam.jojo@sc hmitz-digital.dewrite s:
                    CBFalconer wrote:
                    >Fastro wrote: ** code edited slightly **
                    >>>
                    >>int myfun(char *sourcebuf) {
                    >> char *destbuf;
                    >> char ch;
                    >> while (*sourcebuf != '\0') {
                    >> *destbuf++=*sou rcebuf++; --crashed here
                    >> };
                    >> return 1;
                    >>}
                    >>>
                    >>Can any one explain why it is crashed?
                    >>
                    >Yes. destbuf is uninitialized. It doesn't point to any storage.
                    A step further: because it is uninitialized, it'll contain some garbage
                    value, that, if interpreted as a pointer, will try to access some random
                    memory location. If you're lucky, you don't own that and the OS will carsh
                    the program, if you're unlucky, you'll own it and accessing it will corrupt
                    some data structuturs and you'll only notice the harm it did much later and
                    have major difficulties to find were it went wrong.
                    So be hapy it crashed on you right away...
                    >
                    Bye, Jojo
                    Look up using something like splint. Also consider using a
                    debugger. Both will make it very clear where the error is.



                    I use this all the time and have bound it to me emacs IDE so any emacs
                    users out there, here you are:


                    ,----
                    | (defun do-lint()
                    | (interactive)
                    | (set (make-local-variable 'compile-command)
                    | (let ((file (file-name-nondirectory buffer-file-name)))
                    | (format "%s %s %s"
                    | "splint"
                    | "+single-include -strict -compdef -nullpass -preproc +matchanyintegr al -internalglobs -I/usr/include/gtk-2.0/ -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/cairo/ -I/usr/include/pangomm-1.4/pangomm/"
                    | file
                    | )))
                    | (message compile-command)
                    | (compile compile-command)
                    | )
                    `----

                    Comment

                    • santosh

                      #11
                      Re: doubt on char *

                      Joachim Schmitz wrote:
                      CBFalconer wrote:
                      >Fastro wrote: ** code edited slightly **
                      >>>
                      >>int myfun(char *sourcebuf) {
                      >> char *destbuf;
                      >> char ch;
                      >> while (*sourcebuf != '\0') {
                      >> *destbuf++=*sou rcebuf++; --crashed here
                      >> };
                      >> return 1;
                      >>}
                      >>>
                      >>Can any one explain why it is crashed?
                      >>
                      >Yes. destbuf is uninitialized. It doesn't point to any storage.
                      A step further: because it is uninitialized, it'll contain some
                      garbage value, that, if interpreted as a pointer, will try to access
                      some random memory location. If you're lucky, you don't own that and
                      the OS will carsh the program, if you're unlucky, you'll own it and
                      accessing it will corrupt some data structuturs and you'll only notice
                      the harm it did much later and have major difficulties to find were it
                      went wrong. So be hapy it crashed on you right away...
                      To the OP:

                      This is one reason for those who advocate initialising all pointer
                      objects with their proper values or NULL. Null pointer de-referencing
                      is guaranteed to be caught, instead of causing damage behind your back.

                      Comment

                      • Barry Schwarz

                        #12
                        Re: doubt on char *

                        On Tue, 10 Jun 2008 20:33:42 +0530, santosh <santosh.k83@gm ail.com>
                        wrote:
                        >Joachim Schmitz wrote:
                        >
                        >CBFalconer wrote:
                        >>Fastro wrote: ** code edited slightly **
                        >>>>
                        >>>int myfun(char *sourcebuf) {
                        >>> char *destbuf;
                        >>> char ch;
                        >>> while (*sourcebuf != '\0') {
                        >>> *destbuf++=*sou rcebuf++; --crashed here
                        >>> };
                        >>> return 1;
                        >>>}
                        >>>>
                        >>>Can any one explain why it is crashed?
                        >>>
                        >>Yes. destbuf is uninitialized. It doesn't point to any storage.
                        >A step further: because it is uninitialized, it'll contain some
                        >garbage value, that, if interpreted as a pointer, will try to access
                        >some random memory location. If you're lucky, you don't own that and
                        >the OS will carsh the program, if you're unlucky, you'll own it and
                        >accessing it will corrupt some data structuturs and you'll only notice
                        >the harm it did much later and have major difficulties to find were it
                        >went wrong. So be hapy it crashed on you right away...
                        >
                        >To the OP:
                        >
                        >This is one reason for those who advocate initialising all pointer
                        >objects with their proper values or NULL. Null pointer de-referencing
                        >is guaranteed to be caught, instead of causing damage behind your back.
                        Dereferencing a NULL pointer invokes undefined behavior. Evaluating
                        an indeterminate value (such as dereferencing an uninitialized
                        pointer) invokes undefined behavior. The standard guarantees nothing
                        more for either. It is the system (hardware and OS) and probably the
                        implementation (compiler and run-time library) that determine if
                        either of these two examples of undefined behavior are "caught".


                        Remove del for email

                        Comment

                        • Joachim Schmitz

                          #13
                          Re: doubt on char *

                          Barry Schwarz wrote:
                          On Tue, 10 Jun 2008 20:33:42 +0530, santosh <santosh.k83@gm ail.com>
                          wrote:
                          <snip>
                          >This is one reason for those who advocate initialising all pointer
                          >objects with their proper values or NULL. Null pointer de-referencing
                          >is guaranteed to be caught, instead of causing damage behind your
                          >back.
                          >
                          Dereferencing a NULL pointer invokes undefined behavior. Evaluating
                          an indeterminate value (such as dereferencing an uninitialized
                          pointer) invokes undefined behavior. The standard guarantees nothing
                          more for either. It is the system (hardware and OS) and probably the
                          implementation (compiler and run-time library) that determine if
                          either of these two examples of undefined behavior are "caught".
                          Mind to name implementations that do not catch this? Other than DS9K?

                          Bye, Jojo


                          Comment

                          • Eric Sosman

                            #14
                            Re: doubt on char *

                            santosh wrote:
                            >
                            This is one reason for those who advocate initialising all pointer
                            objects with their proper values or NULL. Null pointer de-referencing
                            is guaranteed to be caught, instead of causing damage behind your back.
                            See Walter Roberson's post for an illustration of the
                            strength of the "guarantee" ...

                            As for the practice of "I've got nothing better to do at
                            the spot where this pointer variable is declared, so I'll
                            initialize it to NULL for safety's sake," you're right that
                            some people advocate it. IM not so HO they make a poor trade
                            by doing so: They gain a (probable) run-time crash at the
                            expense of a (probable) compile-time or lint-time diagnostic.

                            char *p /* = NULL */ , *q /* = NULL */ ;
                            if (something) {
                            if (something_else ) {
                            p = "Hello";
                            if (random_circums tance)
                            q = "world";
                            if (other_random_c ircumstance)
                            q = "Chicago";
                            }
                            else {
                            q = "my ragtime gal";
                            if (whatever)
                            p = "Hello";
                            else
                            p = "Good-bye";
                            }
                            }
                            else ... /* and so on in that vein */

                            printf ("%s %s\n", p, q);

                            If the NULL initializations are included you may get a run-time
                            error at the printf(), if your test cases happen to hit the
                            right combination of circumstances. If the initializations are
                            omitted, many compilers and lints will issue a diagnostic about
                            the use of potentially garbage values, which they almost certainly
                            will not do if the initializations are present.

                            The cost of an error usually increases with the amount of time
                            it remains undetected in the code, so it seems to me that a policy
                            of giving up an inexpensive error-catch in favor of an expensive
                            one is misguided.

                            --
                            Eric Sosman
                            esosman@ieee-dot-org.invalid

                            Comment

                            • pete

                              #15
                              Re: doubt on char *

                              Walter Roberson wrote:
                              In article <g2mdqm$9p0$1@o nline.de>,
                              Joachim Schmitz <jojo@schmitz-digital.dewrote :
                              >Barry Schwarz wrote:
                              >
                              >>Dereferenci ng a NULL pointer invokes undefined behavior. Evaluating
                              >>an indeterminate value (such as dereferencing an uninitialized
                              >>pointer) invokes undefined behavior. The standard guarantees nothing
                              >>more for either. It is the system (hardware and OS) and probably the
                              >>implementatio n (compiler and run-time library) that determine if
                              >>either of these two examples of undefined behavior are "caught".
                              >
                              >Mind to name implementations that do not catch this?
                              I do mind, but I'll do it anyway.
                              > Other than DS9K?
                              >
                              SGI IRIX64 does not catch dereferencing a NULL pointer.
                              new.c freezes on Windows XP, MSVC++ V5.0

                              C:\Program Files\DevStudio \SharedIDE\bin\ Debug>new
                              /* BEGIN new.c output */
                              ^C
                              C:\Program Files\DevStudio \SharedIDE\bin\ Debug>




                              /* BEGIN new.c */

                              #include <stdio.h>

                              int main(void)
                              {
                              char *a = NULL;

                              puts("/* BEGIN new.c output */");
                              if (*a == 0) {
                              puts("wow");
                              }
                              puts("/* END new.c output */");
                              return 0;
                              }

                              /* END new.c */

                              --
                              pete

                              Comment

                              Working...