Thread: How To Chk Uninitialized Pointer

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    8

    How To Chk Uninitialized Pointer

    Hi C Cders,
    I have a query in C Pointers.
    I have written a simple strcpy program.
    So from src to dest, it copies.
    Code:
    #include <stdio.h>
    #include <conio.h>
    void my_strcpy(char *dst, char *src)
    {
         if(src == NULL)
         {
                printf("Null Assignment:\n");
                return;
                }
         while(*src != '\0')
         {
                    *dst = *src;
                    src++;
                    dst++;
                    }
         *dst = '\0';
     }
    int main()
    {
        char dst[20];
        char *src = "Hello";
        my_strcpy(dst, src);
        printf("%s\n", dst);
        getch();
    }
    Now if I do not assign the src string say it is like
    Code:
    char *src;
    Then in the printf statement it will print some junk chars.
    So how to handle this type of cases.
    As this case src may hold any address, it may be either NULL or some arbitrary address. So with NULL checking, it will not suffice.
    So in the my_strcpy() what check need to add?

    Thanks in advance for your help.

    With regards,
    u_peerless

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The best you can do within your code itself is check for a null pointer.

    You can also use code analysis tools to help you detect such errors, but such tools may be expensive.
    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

  3. #3
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Well, first of all, shouldn't you malloc() memory for char *src? If you don't you might get segmentation faults. Though this depends on the system.

    If you malloc() memory it will be randomly initialized to something. So there is no sense saying "checking" for junk since what is junk and what is not is human-like not machine like.

    If the above works, then it automatically gets memory to store a string "Hello". So if you didn't initialize it wouldn't allocate memory so it would give you a nice Seg Fault
    Last edited by C_ntua; 06-19-2008 at 08:14 AM.

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I think you can't check for that condition.

    Another thing that your function doesn't check for (and cannot check as far as I know) is that the source buffer is actually null-terminated and you don't simply walk over the end of it, and similarly you don't know the size of the destination buffer.

    So it in fact adds very little safety. I imagine a programmer either would know that a buffer is valid, and if they are unsure whether a char pointer might be NULL, they could check it themselves before calling strcpy. (In typical use cases checks like these might be a bit unnecessary.)

    In addition, if a function can fail printing a message is not the best response. Sure, the user may be able to read the message (as long as there is a console) but your program cannot detect that anything went wrong because your function doesn't tell it that.

    Also, the signature is a bit wrong. It should be:
    Code:
    void my_strcpy(char *dst, const char *src)
    Last edited by anon; 06-19-2008 at 08:16 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  5. #5
    Registered User
    Join Date
    Jun 2008
    Posts
    8
    Quote Originally Posted by laserlight View Post
    The best you can do within your code itself is check for a null pointer.

    You can also use code analysis tools to help you detect such errors, but such tools may be expensive.
    When I am using unintialized pointer, then it may have any value either NULL or arbitrary value, It can be seen if I do a printf statement on this unitialized pointer, then it will display some garbage value. So only checking NULL value will not suffice I suppose.
    So I need to handle it in some other way. I want to know that.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by C_ntua
    Well, first of all, shouldn't you malloc() memory for char *src? If you don't you might get segmentation faults.
    No need, since src points to (the first character of) a string literal. Of course, along the lines of what anon pointed out, src should be a pointer to const char because it points to a string literal.

    Quote Originally Posted by u_peerless
    When I am using unintialized pointer, then it may have any value either NULL or arbitrary value, It can be seen if I do a printf statement on this unitialized pointer, then it will display some garbage value. So only checking NULL value will not suffice I suppose.
    Unfortunately, that is true, but still, checking for NULL is the best you can do within your code. You can also not check for NULL, and simply make it a pre-condition that the pointers are not null pointers.

    Quote Originally Posted by u_peerless
    So I need to handle it in some other way. I want to know that.
    Enforce the rule that all variables must be properly initialised before use. Fire programmers who violate this rule. Alternatively, use a tool like PC-Lint.
    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

  7. #7
    Registered User
    Join Date
    Jun 2008
    Posts
    8
    Hi anon, you are correct, I did not do all this checkings. My intention was to know this thing. I have come to know this.
    Thanks all for your comments.

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    There is no generic way to determine if a pointer is valid - you can possibly write some code (or rather, quite a lot of code) that checks if you can read (or write) to a pointer. But it's very tricky to get this right, and it still doesn't catch when the user gets it wrong and writes to memory that is valid to access, but not correctly owned by the user's code (e.g. a pointer to a char array return from a function or a pointer that was malloced, but now freed - so the memory is no longer available - but since it's still pointing to memory that CAN be accessed, there's no way to detect this).

    Checking for NULL is a good thing to do. Anything else, you just let the programmer discover that it's not working and let him/her figure out why. There is so little that you can sensibly do in other ways that it's not worth the effort of trying to catch those situations.

    --
    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.

  9. #9
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Well, let me make my point more clear.

    Technically you want to initialize a string not a pointer. I know it is the same, just to point out the logic behind things. What is the first thing to do before initializing? It is creating. So you should allocate memory for your string. You do that as pointed out by laserlight by assigning the pointer to a constant string. You do two things. Allocate memory and initialize. If you wanted to create and not initialize you would malloc().

    Technically if you want to initialize a pointer you give NULL or an a value (int). If you don't initialize it the system does for you. So there is no actual un-initialized pointer.

    My whole point is that in C you pass strings with the help of a pointer. If you just pass a pointer that doesn't so to an allocated memory then that is a serious error.

    So, what I am trying to say is this: Fire the programmer because he passed a pointer that doesn't point to an allocated memory. Don't fire him because he didn't initialize the pointer :P

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, but it's perfectly possible in C to have uninitialized variables. There is nothing in the language itself that is forcing the pointer to be initialized. It is also possible to have valid code that never uses an uninitialized variable, but where you don't need to initialize the variable at the point of declaration - because that would unnecessarily write to the variable when it's not actually used.

    It is of course incorrect to USE an uninitialized variable for anything other than assigning it with a new value.

    Compilers do have the ability to understand uninitialized variables in most cases, but it's possible to fool the compiler both into false negatives and false positives of "uninitialized variable".

    --
    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.

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    C++ might be able to detect uninitialized pointers (via classes), but in C, it would be a huge responsibility for the programmer, probably using a lot of functions for assigning, and checking and such.
    And they would have to work on multiple types, maybe. Or maybe not.
    Regardless, check for NULL is usually the best C can do and is often sufficient.
    Initialize all pointers to NULL and you should have little trouble with that particular problem. Hopefully anyway.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User slingerland3g's Avatar
    Join Date
    Jan 2008
    Location
    Seattle
    Posts
    603
    This issue of uninitialized pointers has been pretty much addressed already. I just wanted to stress the point that it is up to the programmer to insure that pointers are first initialized.

    Code:
    char *src;      /* very bad  = undefined behaviour */
    assign as:

    Code:
    char *src = NULL;
    One can not simply test whether a pointer is valid or not when passed to a function call.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  2. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  3. Parameter passing with pointer to pointer
    By notsure in forum C++ Programming
    Replies: 15
    Last Post: 08-12-2006, 07:12 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM