C Neophyte needs guidance to String/Char processing

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • UncleRic
    New Member
    • Sep 2006
    • 10

    C Neophyte needs guidance to String/Char processing

    Environment: OS X (v10.4.10) running gnu gcc 4.0.1 compiler.

    Greetings...
    I'm toying with functions passing strings written in pure ANCI C. I've written a simple 'C' program below to develop an understanding how C works.

    Questions:
    1) What will be in variable 'q'?
    2) Is there another way to write: char* myFunction() {}?

    Regards,
    Ric.

    BTW: the GNU compiler gives me a warning that 'myFunction()' returns the address of a local variable.
    ------------------------------------------------------------------------------------------------------
    Code:
    #include <stdio.h>
    #include <string.h>
    
    char *myFunction();
    
    int main() { 
       char * b, q, *r;
       b=myFunction();
       q=*b;  // <--- what will 'q' contain?   
       printf("\nDone.\n");
       return 0;
    } // end main() 
    
    // ----------------------------------------------------
    
    char* myFunction() { 
       char str[15]; 
       strcpy(str, "Hello, Ric!\n");
       printf("Inside myFunction: %s",str);
       return (char *) str;
    }
    =============== =============== =============== ===========

    Here's the output (via Mac OS X using gcc 4.0.1 compiler):
    Code:
    [/Users/Ric/workarea/C workspace/c_strings]./myTest
    Inside myFunction: Hello, Ric!
    
    Done.
  • gsi
    New Member
    • Jul 2007
    • 51

    #2
    Hi ,
    The program's result is undefined. A local pointer is returned(Arrays are implicitly passed and returned as pointers in c). Hence on scope exit, the pointer is no longer a valid address in memory. In line 9, q may still have 'H' in it, if no other activation record has been pushed on to the stack.

    One way of doing this is to create an array (Either heap or stack) from main, pass that to the function , do a strcpy on the passed arrayand return the same.

    like,
    [code=cpp]

    int main(void){
    //your initialization' s
    char str[15];//Dynamic memory allocation can also be done.
    b=myFunction(st r);
    // your code
    }
    char* myFunction(char *str) {
    strcpy(str, "Hello, Ric!\n");
    printf("Inside myFunction: %s",str);
    return (str);
    }
    [/code]

    Thanks,
    gsi.

    Comment

    • beyondgravity
      New Member
      • Aug 2007
      • 1

      #3
      hi, i'm a neophyte in this community. i already searched most of the web sites to find codes on hashing in c language but still i failed, all i found were codes in java programming.. anyways, can you provide me examples and explanations on the following?:
      >hashing methods:
      *division methods
      *middle square method
      *multiplication method
      *fibonacci hashing

      thanks in advance...
      jay-em

      and p.s. can you send it directly to my e-mail address <Email removed by MODERATOR, according to posting guidelines>
      Last edited by Ganon11; Aug 30 '07, 07:41 PM. Reason: Removing email address.

      Comment

      • UncleRic
        New Member
        • Sep 2006
        • 10

        #4
        Originally posted by gsi
        Hi ,
        The program's result is undefined. A local pointer is returned(Arrays are implicitly passed and returned as pointers in c). Hence on scope exit, the pointer is no longer a valid address in memory. In line 9, q may still have 'H' in it, if no other activation record has been pushed on to the stack.

        One way of doing this is to create an array (Either heap or stack) from main, pass that to the function , do a strcpy on the passed arrayand return the same.

        like,
        [code=cpp]

        int main(void){
        //your initialization' s
        char str[15];//Dynamic memory allocation can also be done.
        b=myFunction(st r);
        // your code
        }
        char* myFunction(char *str) {
        strcpy(str, "Hello, Ric!\n");
        printf("Inside myFunction: %s",str);
        return (str);
        }
        [/code]

        Thanks,
        gsi.
        Thanks for your speedy reply.
        I read your message and began working on what you told me, via Apple's XCode (GNU gcc compiler). I've expanded the code to the following:

        Code:
        #include <stdio.h>
        #include <string.h>
        
        char *myFunction(); 
        char *anotherfunction(char *b);
        
        int main (int argc, const char * argv[]) {
            char * b, q, *r; 
            b=myFunction();
            q = *b;    
             r= anotherfunction(b);    
            // .....     
            return 0;
        }
        
        // --------------------------------------------------------------------------------------
        
        char *myFunction() {
        	char str[8];
                strcpy(str, "Hello");
        	return (char *) str;
        }   
        
        // --------------------------------------------------------------------------------------
        
        char *anotherfunction(char *b)  {
            printf("Inside anotherfunction: %s",b);
           return (char *) b;	
        } // end anotherfunction().
        The following is what I got via the dubugger:
        Code:
        Program loaded.
        sharedlibrary apply-load-rules all
        run
        [Switching to process 648 local thread 0xf03]
        Running…
        Pending breakpoint 1 - ""main.c:25" resolved
        (gdb) print b
        $1 = 0xbffff5d8 "\030\366\377\277X\035"
        (gdb) print q
        $2 = 72 'H'
        (gdb) print r
        $3 = 0xbffff5d8 "\030\366\377\277X\035"
        (gdb) cont
        Inside anotherfunction: Hello
        Debugger stopped.
        Program exited with status value:0.Continuing.
        So the value of 'b' as returned by myFunction() is some hex address.
        The value of 'q' is the first char of the array 'str' (i.e., str[0]).

        ------

        Even though the compiler gives a warning that I'm passing the address of a local variable, it DOES pass that value.

        But since we get that warning, I'm assuming that this value won't always be available. So, under what conditions might this not be so?

        Regards,

        Ric.

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by UncleRic
          But since we get that warning, I'm assuming that this value won't always be available. So, under what conditions might this not be so?
          The C Standard has a nice definition about that: it defines 'undefined behaviour'.
          What you just did in your program causes undefined behaviour and anything can
          happen then. You're just lucky that you got reasonable output when you ran
          your program; but maybe tomorrow it won't behave reasonable anymore. Nobody
          knows and don't rely on its behaviour totday: it is undefined.

          Either malloc() memory in that function and fill it with a ('\0' terminated) string or
          pass a buffer to that function which is used by that function to put a string in.
          Returning the address of a local variable is a real nono and you should never
          rely on it.

          kind regards,

          Jos

          Comment

          Working...