Thread: Differnce between C and Java returning an Object reference/pointer

  1. #1
    Registered User
    Join Date
    Sep 2011
    Location
    India
    Posts
    27

    Question Differnce between C and Java returning an Object reference/pointer

    In C we know that the memory allocated locally inside a function will vanish when the function returns

    Code:
    char *getName()
    {
    char name[]="Sumit";
    return name
    }

    The caller of the function will get a pointer to the array.Although the pointer points a garbage unknown location since the array was local, it has now been destroyed.



    Now I have a doubt the same thing works in Java

    Code:
    public String getName()
    {
    String name="Sumit"; //name here is local as above;memory allocated for the object locally
    return name;
    }

    The caller of the method will correctly get the String returned.

    What is the difference in the mechanism of returning pointer in C and reference in Java?

    Hope I m made my point clear.
    Eagerly waiting for reply.

    Regards

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The difference here isn't in the way the pointer is returned really. The difference is what you are actually returning. Or rather, what type of object you are trying to return. In the first example, you are returning a local variable. If you were actually allocating some memory dynamically, copying your characters into that block of memory, and then returning that - then you would be like what your Java example does; assuming the Java example is actually correct.
    Code:
    char *getName( void )
    {
        char buf[ BUFSIZ ] = { "some name" };
        char *s = NULL;
        s = malloc( strlen( buf ) + 1 );
        strcpy( s, buf );
        return s;
    }
    Something like that. Of course you need to free that when you are done.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Do you understand why this C version works?
    Code:
    const char *getName()
    {
        const char *name="Sumit";
        return name;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Salem View Post
    Do you understand why this C version works?
    Code:
    const char *getName()
    {
        const char *name="Sumit";
        return name;
    }
    I was over thinking it. I suppose we could even shorten that:
    Code:
    char *getName( void )
    {
        return "Sumit";
    }

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Sep 2011
    Location
    India
    Posts
    27
    This C version does not work. It returns garbage (i.e the pointer points to garbage, not to memory conatainig the desired string)

    Quote Originally Posted by Salem View Post
    Do you understand why this C version works?
    Code:
    const char *getName()
    {
        const char *name="Sumit";
        return name;
    }

  6. #6
    Registered User
    Join Date
    Sep 2011
    Location
    India
    Posts
    27
    Thanks @quzah for your quick reply.

    You mean to say that the memory allocated this way is not dynamic
    Code:
    char name[]="Sumit";
    What we call this type of memory allocation.

    Moreover you mean to say that dynamic memory allocated does not have a restricted local (automatic scope)?
    Am i right in saying above statements.

    Regards



    Quote Originally Posted by quzah View Post
    The difference here isn't in the way the pointer is returned really. The difference is what you are actually returning. Or rather, what type of object you are trying to return. In the first example, you are returning a local variable. If you were actually allocating some memory dynamically, copying your characters into that block of memory, and then returning that - then you would be like what your Java example does; assuming the Java example is actually correct.
    Code:
    char *getName( void )
    {
        char buf[ BUFSIZ ] = { "some name" };
        char *s = NULL;
        s = malloc( strlen( buf ) + 1 );
        strcpy( s, buf );
        return s;
    }
    Something like that. Of course you need to free that when you are done.


    Quzah.

  7. #7
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Moreover you mean to say that dynamic memory allocated does not have a restricted local
    In general, when you allocate memory, it is done on the heap.
    But variable declarations get memory on the stack, making them local in scope.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by sumit180288
    Now I have a doubt the same thing works in Java
    (...)
    The caller of the method will correctly get the String returned.
    You could say that the local String reference variable is destroyed, but the String object itself is not necessarily destroyed when the method returns. It may be destroyed at some point when it is clear that there are no references that refer to the String object. In general, object lifetime in Java is not deterministically associated with the scope of a variable.

    Quote Originally Posted by sumit180288
    This C version does not work. It returns garbage (i.e the pointer points to garbage, not to memory conatainig the desired string)
    Look more carefully at the type of name and what name refers to before jumping to that conclusion.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User gardhr's Avatar
    Join Date
    Apr 2011
    Posts
    151
    Quote Originally Posted by sumit180288 View Post
    This C version does not work. It returns garbage (i.e the pointer points to garbage, not to memory conatainig the desired string)
    It does work, and here's why: the string literal "Sumit" is effectively a global/static variable, so returning it's address (stored in the pointer 'name', that is) it perfectly safe. Now had you declared it:

    Code:
    char name[ ] = "Sumit";
    Here, the string literal is copied into a local array of bytes and then a pointer to the latter returned to the caller, which is of course unsafe.

    Dynamic allocation (such as using malloc) is similar to the first case, except now we are using a library routine that serves up pieces of a global/static chunk of data which can be safely returned to the caller.
    Last edited by gardhr; 09-07-2011 at 12:14 AM. Reason: clarification

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > This C version does not work. It returns garbage (i.e the pointer points to garbage, not to memory conatainig the desired string)
    What crap are you smoking?
    Code:
    $ cat baz.c
    #include <stdio.h>
    const char *getName()
    {
        const char *name="Sumit";
        return name;
    }
    int main ( ) {
      printf("%s\n",getName());
      return 0;
    }
    $ gcc -W -Wall -ansi -pedantic baz.c
    $ ./a.out 
    Sumit
    $
    This is NOT the same as your array code in your first post.

    If you're still under the illusion that arrays and pointers are the same thing in C, then read this.
    Arrays and Pointers
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    Registered User
    Join Date
    Sep 2011
    Location
    India
    Posts
    27
    Code:
    char *f()
            {
                    char buf[10];
                    /* ... */
                    return buf;
            }
    According to a link http:///www.lysator.liu.se/c/c-faq/c-3.html, the above set of statements will result in garbage set of values returned.

    Quote Originally Posted by Salem View Post
    > This C version does not work. It returns garbage (i.e the pointer points to garbage, not to memory conatainig the desired string)
    What crap are you smoking?
    Code:
    $ cat baz.c
    #include <stdio.h>
    const char *getName()
    {
        const char *name="Sumit";
        return name;
    }
    int main ( ) {
      printf("%s\n",getName());
      return 0;
    }
    $ gcc -W -Wall -ansi -pedantic baz.c
    $ ./a.out 
    Sumit
    $
    This is NOT the same as your array code in your first post.

    If you're still under the illusion that arrays and pointers are the same thing in C, then read this.
    Arrays and Pointers

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by sumit180288
    According to a link http:///www.lysator.liu.se/c/c-faq/c-3.html, the above set of statements will result in garbage set of values returned.
    Effectively yes, though strictly speaking there is undefined behaviour if the return value is used. It is good that you recognise this, but you should also recognise that your claim that "this C version does not work" is not backed up by this example, because the essential part of the code is different.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Sep 2011
    Location
    India
    Posts
    27
    OK i got ur point
    Can you tell me what is the difference between these two codes:
    Code:
    char *f()
    {
    char *name="Sumit";
    return name;
    }
    and
    Code:
    char *f()
    {
    char name[]="Sumit";
    return name;
    }
    WHY the FIRST VERSION WORKS???


    Quote Originally Posted by Salem View Post
    > This C version does not work. It returns garbage (i.e the pointer points to garbage, not to memory conatainig the desired string)
    What crap are you smoking?
    Code:
    $ cat baz.c
    #include <stdio.h>
    const char *getName()
    {
        const char *name="Sumit";
        return name;
    }
    int main ( ) {
      printf("%s\n",getName());
      return 0;
    }
    $ gcc -W -Wall -ansi -pedantic baz.c
    $ ./a.out 
    Sumit
    $
    This is NOT the same as your array code in your first post.

    If you're still under the illusion that arrays and pointers are the same thing in C, then read this.
    Arrays and Pointers

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > According to a link http:///www.lysator.liu.se/c/c-faq/c-3.html, the above set of statements will result in garbage set of values returned.
    Like I said, until you recognise that char* and char[] are different things, you're just going to be confused.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  15. #15
    Registered User
    Join Date
    Sep 2011
    Location
    India
    Posts
    27
    @Salem. Sorry to say i didn't see the pointer version. I thought u are asking about the array version.
    I am also not knowing why this verison works?
    Anyone plz clear this doubt.

    Regards

    Quote Originally Posted by Salem View Post
    Do you understand why this C version works?
    Code:
    const char *getName()
    {
        const char *name="Sumit";
        return name;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning object by value or smart pointer
    By mrpringle in forum C++ Programming
    Replies: 3
    Last Post: 08-29-2010, 02:13 AM
  2. Returning an object with a dynamic pointer
    By maxsthekat in forum C++ Programming
    Replies: 11
    Last Post: 09-16-2009, 01:52 PM
  3. trouble returning an object by reference
    By fisheromen1031 in forum C++ Programming
    Replies: 14
    Last Post: 02-19-2008, 11:10 PM
  4. Object reference not set to instance of an object
    By patricio2626 in forum C++ Programming
    Replies: 6
    Last Post: 10-26-2006, 08:12 AM
  5. ERRPR: Object reference not set to an instance of an object
    By blackhack in forum C++ Programming
    Replies: 1
    Last Post: 07-13-2005, 05:27 PM

Tags for this Thread