Initializing pointers always necessary?

This is a discussion on Initializing pointers always necessary? within the C Programming forums, part of the General Programming Boards category; I've been encountering info lately that seems to suggest that *all* pointers in C code should always be initialized. Does ...

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    67

    Initializing pointers always necessary?

    I've been encountering info lately that seems to suggest that *all* pointers in C code should always be initialized. Does anyone know if this is always true/necessary?

    I'm also confused about *how* to correctly initialize pointers; I've searched for examples, and they vary from recommending that pointers be initialized to NULL, to setting them to the address of a variable. Is one or the other technique always correct, or will it depend on the application?

    For my own code, the only pointers I have are FILE pointers. e.g.:

    FILE *fid1, *fid2;

    When I'm done using them, I do fclose(fid1); and fclose(fid2);

    My questions:
    a) for my FILE pointers, how do I correctly initialize these?
    b) Is there anything different/additional that I need to do when I'm done using these initialized pointers, beyond calling fclose( )? I read in one place that you're supposed to set the pointers to 0 after calling fclose( ), but am not sure if this is true, and if true, I'm wondering about the correct syntax for this.

    I should note that my current code is giving weird output, e.g. variables that should have values have NAN or nonsense values; I'm thinking that possibly my noninitialized pointers *may* have something to do with this. (All of my other regular variables are initialized to 0 or 0.0, depending on type).

    Thanks for your input.
    Last edited by CodeKate; 08-16-2010 at 11:17 AM.

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    There's no right or wrong when it comes to initializing pointers. Pointers are just like any other variable: if you don't explicitly set them to a value, the value will be undefined (essentially random). If you then accidentally access the variable, very bad things can happen.

    Sometimes people recommend that pointers be assigned to NULL, the universal value meaning "this pointer doesn't point at anything", because a lot of code already checks for NULL pointers. For example, if you call free(NULL), it's guaranteed to do nothing. If you passed an uninitialized pointer in who knows what would happen.

    It's really just a safeguard against programmer error. If you initialize pointers to a reasonable value, it's less likely that an uninitialized pointer will cause a system crash sometime in the future.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    Thanks for your input, dwks.

    I'm not too keen on initializing to NULL if I can help it; it seems to me that there is a lot of opportunity for things to go wrong if my code expects my pointers to have a value, and instead they're pointing to nothing/NULL. Am I correct in this concern?

    When you recommend initializing my pointers to a "reasonable value", can you please provide an example? Pointers have always been confusing to me, and I'm not sure what would be considered a reasonable value. For my example, FILE *fid1, *fid2, can you give an explicit example of initializing to reasonable values? Will these be characters, or numbers? Any help with syntax and specifics is appreciated.

    If it's relevant, my use of my file pointers is the typical expected use, e.g.
    fid1 = fopen("output.log","w");
    fprintf(fid1, "....", values);
    fclose(fid1);
    Last edited by CodeKate; 08-16-2010 at 11:31 AM.

  4. #4
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    I'm not too keen on initializing to NULL if I can help it; it seems to me that there is a lot of opportunity for things to go wrong if my code expects my pointers to have a value, and instead they're pointing to nothing/NULL. Am I correct in this concern?
    When you don't initialize a pointer and then try to use it, you have 3 problems:

    - It might be pointing at memory you don't have access to, in which case it causes a segmentation fault and crashes your program
    - It might be pointing at real data, and if you don't know what it's pointing to, you're causing unpredictable (and very hard to debug) changes to your data.
    - You have no way of knowing if it's been initialized or not - because how do you tell the difference between a valid address and the address that happened to be there when you declared the pointer?

    Initializing every pointer to NULL seriously decreases or eliminates those problems:

    - If I try and use it, it will still segfault, but at least I can test if it's NULL and act accordingly - I can know that it WILL segfault, and do something else. If it's a random value, I don't know anything until it crashes.
    - If you initialize it to NULL, I can't make it point to data unless I explicitly tell it to. So I only modify what I meant to.
    - As implied above, I can tell when I've initialized it and when I haven't, and make a decision.

    Obviously it's a matter of style, and it is possible to write an application where variables are only initialized to their intended value, but I feel it is safer and easier to initialize them to NULL always. Even the best programmers make typos - NULL makes it easier to know when that's happened.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,753
    If you are compiling with respect to C99, then you can take advantage of the ability to mix declarations and code, and thus declare variables near first use. You would write:
    Code:
    FILE *fid1 = fopen("output.log", "w");
    even if there was some non-declaration code before this line.

    But if you want the code to be compilable with respect to C89 too, then this is not always feasible. You can still declare variables near first use, except that "near first use" may mean the start of the block in which the variable is first used. Consequently, if you do not declare variables too far from where they are first used (e.g., you write functions that do one thing and do it well), you can still get away with not initialising the variables as there is minimal risk that you will use the variable before it has been given an initial value. If you do want to initialise them anyway, yet cannot initialise them with the values that they are supposed to have, then for pointers NULL is a reasonable value. Random "characters, or numbers" would be unreasonable.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    That was very instructive, Sean. Thanks.

    >> Obviously it's a matter of style, and it is possible to write an application where variables are only initialized to their intended value, but I feel it is safer and easier to initialize them to NULL always.

    I followed your advice and initialized my pointers to NULL, and indeed found that I can still use them normally in my code without errors. However, I'm confused by your comment, "If I try and use it, it will still segfault..." -- are you saying that if the pointers are used *incorrectly* in the code, after they've been initialized to NULL, it will cause a segfault?

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I don't initialize FILE pointers to anything, before they're assigned their value from fopen().

    Where you can get into trouble is with stuff like:
    Code:
    int *pint;
    
    //some other code.
    //more code
    
    *pint = 15;
    Because you forgot that *pint was never given a valid address.

    Making an assignment of a pointer to null, is no help (to me, so far) - the program is still not going to work reliably, until you make the CORRECT assignment. All before you dereference the pointer.

  8. #8
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    >> If you do want to initialise them anyway, yet cannot initialise them with the values that they are supposed to have, then for pointers NULL is a reasonable value. Random "characters, or numbers" would be unreasonable.

    Thanks for the clarification, laserlight. Some of the examples I came across seemed to initialize pointers to arbitrary variable addresses within the code (e.g. fid1 = &myval1), which was confusing to me.

  9. #9
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    >> Making an assignment of a pointer to null, is no help (to me, so far) - the program is still not going to work reliably, until you make the CORRECT assignment.

    I don't mean to be obtuse, but can you clarify what you mean by the "correct" assignment? I read your post as saying that, as long as I'm only using file pointers in the way I stated, there is no need to initialize them to NULL... if so, would you consider my pointers to be "correctly" assigned?

  10. #10
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    are you saying that if the pointers are used *incorrectly* in the code, after they've been initialized to NULL, it will cause a segfault?
    When I say used, I mean dereference. Anytime you dereference a NULL pointer, you're going to get a segfault, because you're accessing memory you shouldn't access. It's the same situation when you try and accesses memory addresses that aren't allocated to your program.

  11. #11
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    >> Anytime you dereference a NULL pointer, you're going to get a segfault

    Ok, so as long as I use and assign value to each of my initialized-to-NULL pointers, I will have no problem dereferencing them at the end of my code. After initializing my pointers to NULL, my code seems to run fine with my calls to fclose( ) [although this initialization unfortunately hasn't fixed my buggy values].

  12. #12
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    Right. As someone mentioned, earlier, a lot of code is written to expect NULL to mean an uninitialized value. A function might do this:

    Code:
    int doSomething(int* x) {
        if(x == NULL) {
            return ERROR_CODE;
        }
        ...
        // do something with x
        ...
        return SUCCESS;
    }
    If the function is passed a NULL, it knows that you've done something you shouldn't have done (you passed a pointer with the value NULL, rather than a real, intentional value), and so it cane return an error and fail gracefully. If it was passed a random value or other invalid pointer, it would try and do something with it, segfault, and crash the entire program.

  13. #13
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,623
    Quote Originally Posted by Adak View Post
    Making an assignment of a pointer to null, is no help (to me, so far) - the program is still not going to work reliably, until you make the CORRECT assignment. All before you dereference the pointer.
    I find this a ridiculous appeasement, especially for noobs. As sean mentioned, if the pointer was initialized to NULL, then you would see that the pointer is NULL in your debugger. Furthermore, you could check for NULL before dereferencing a pointer and fail or just do an assert.
    All good options which fail if you don't initialize them.

    So the point is, unless you have a valid value to initialize a pointer with, always initialize it to NULL. And by valid, I mean something in context such as something returned from fopen if you have a FILE*.
    Last edited by Elysia; 08-16-2010 at 12:40 PM.
    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.

  14. #14
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    Thanks, Elysia. That was a very straightforward analysis.

  15. #15
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    a) for my FILE pointers, how do I correctly initialize these?
    Yes, of course just like you need to correctly initialize other type variables.

    b) Is there anything different/additional that I need to do when I'm done using these initialized pointers, beyond calling fclose( )? I read in one place that you're supposed to set the pointers to 0 after calling fclose( ), but am not sure if this is true, and if true, I'm wondering about the correct syntax for this.
    No, it's not necessary to set to 0 after calling fclose().
    File pointer are just pointer. assignment operator(=) is all you need.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. size of struct with pointers and function pointers
    By sdsjohnny in forum C Programming
    Replies: 3
    Last Post: 07-02-2010, 05:19 AM
  2. Replies: 7
    Last Post: 05-19-2010, 02:12 AM
  3. pointers to arrays
    By rakeshkool27 in forum C Programming
    Replies: 1
    Last Post: 01-24-2010, 06:28 AM
  4. trouble initializing a dynamic array of pointers to NULL
    By supernater in forum C++ Programming
    Replies: 8
    Last Post: 09-13-2009, 04:47 PM
  5. Staticly Bound Member Function Pointers
    By Polymorphic OOP in forum C++ Programming
    Replies: 29
    Last Post: 11-28-2002, 12:18 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21