Thread: Pointer issue

  1. #1
    Registered User
    Join Date
    Sep 2008
    Posts
    14

    Question Pointer issue

    Hello guys,

    Am I missing anything here?

    Code:
    struct whatever
    {
        char data[100];
    };
    
    void something(struct whatever *wp, char **data)
    {
        *data = wp->data;
        return;
    }
    
    void get_it(struct whatever *wp)
    {
        char *stuff = NULL;
        something(wp, &stuff);
        printf("The stuff is: %s\n", stuff);
        return;
    }
    Is something(); prone to some kind of error? Like something being corrupted, etc leading to `stuff' being corrupted too somehow...

    Thanks in advance.

    Best Regards.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    In your program as given, stuff can not be corrupted because stuff never has a valid value to begin with. If you plan to put something into the location pointed to by stuff, you must first acquire actual space for stuff to point to (using malloc).

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I see nothing wrong in the code you have just posted.

    There are potential problems with returning or fetching pointers to local variables, if the struct whatever "goes away" because you leave the function it is local to, or if you free it's memory, you can still have a pointer to the contents of the struct - but the struct is no longer there, so you are pointing "in the weeds". This can cause hideous problems where code randomly works sometimes and not other times (depending on what else has happened to the "weeds").

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems passing a file pointer to functions
    By smitchell in forum C Programming
    Replies: 4
    Last Post: 09-30-2008, 02:29 PM
  2. sorting with pointer of pointers to array
    By dunpealslyr in forum C++ Programming
    Replies: 6
    Last Post: 10-01-2007, 11:26 PM
  3. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 02:19 AM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. file pointer
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-11-2001, 03:52 PM