开发者

initializing char pointers

I have a char pointer which would be used to store a string. It is used later in the program.

I have declared and initialized like this:

char * p = NULL;

I am just wondering开发者_JAVA百科 if this is good practice. I'm using gcc 4.3.3.


Yes, it's good idea. Google Code Style recommends:

  1. To initialize all your variables even if you don't need them right now.
  2. Initialize pointers by NULL, int's by 0 and float's by 0.0 -- just for better readability.

    int i = 0;
    double x = 0.0;
    char* c = NULL;
    


It is good practice to initialize all variables.


You cannot store a string in a pointer.

Your definition of mgt_dev_name is good, but you need to point it somewhere with space for your string. Either malloc() that space or use a previously defined array of characters.

char *mgt_dev_name = NULL;
char data[4200];

/* ... */

mgt_dev_name = data; /* use array */

/* ... */

mgt_dev_name = malloc(4200);
if (mgt_dev_name != NULL) {
    /* use malloc'd space */
    free(mgt_dev_name);
} else {
    /* error: not enough memory */
}


If you're asking whether it's necessary, or whether it's a good idea to initialize the variable to NULL before you set it to something else later on: It's not necessary to initialize it to NULL, it won't make any difference for the functionality of your program.

Note that in programming, it's important to understand every line of code - why it's there and what exactly it's doing. Don't do things without knowing what they mean or without understanding why you're doing them.


Another option is to not define the variable until the place in your code where you have access to it's initial value. So rather then doing:

char *name = NULL;

...

name = initial_value;

I would change that to:

...

char *name = initial_value;

The compiler will then prevent you from referencing the variable in the part of the code where it has no value. Depending on the specifics of your code this may not always be possible (for example, the initial value is set in an inner scope but the variable has a different lifetime), moving the definition as late as possible in the code prevents errors.

That said, this is only allowed starting with the c99 standard (it's also valid C++). To enable c99 features in gcc, you'll need to either do:

gcc -std=gnu99

or if you don't want gcc extensions to the standard:

gcc -std=c99


No, it is not a good practice, if I understood your context correctly.

If your code actually depends on the mgt_dev_name having the initial value of a null-pointer, then, of course, including the initializer into the declaration is a very good idea. I.e. if you'd have to do this anyway

char *mgt_dev_name;

/* ... and soon after */
mgt_dev_name = NULL;

then it is always a better idea to use initialization instead of assignment

char *mgt_dev_name = NULL;

However, initialization is only good when you can initialize your object with a meaningful useful value. A value that you will actually need. In general case, this is only possible in languages that allow declarations at any point in the code, C99 and C++ being good examples of such languages. By the time you need your object, you usually already know the appropriate initializer for that object, and so can easily come up with an elegant declaration with a good initializer.

In C89/90 on the other hand, declarations can only be placed at the beginning of the block. At that point, in general case, you won't have meaningful initializers for all of your objects. Should you just initialize them with something, anything (like 0 or NULL) just to have them initialized? No!!! Never do meaningless things in your code. It will not improve anything, regardless of what various "style guides" might tell you. In reality, meaningless initialization might actually cover bugs in your code, making it the harder to discover and fix them.

Note, that even in C89/90 it is always beneficial to strive for better locality of declarations. I.e. a well-known good practice guideline states: always make your variables as local as they can be. Don't pile up all your local object declarations at the very beginning of the function, but rather move them to the beginning of the smallest block that envelopes the entire lifetime of the object as tightly as possible. Sometimes it might even be a good idea to introduce a fictive, otherwise unnecessary block just to improve the locality of declarations. Following this practice will help you to provide good useful initializers to your objects in many (if not most) cases. But some objects will remain uninitialized in C89/90 just because you won't have a good initializer for them at the point of declaration. Don't try to initialize them with "something" just for the sake of having them initialized. This will achieve absolutely nothing good, and might actually have negative consequences.

Note that some modern development tools (like MS Visual Studio 2005, for example) will catch run-time access to uninitialized variables in debug version of the code. I.e these tools can help you to detect situations when you access a variable before it had a chance to acquire a meaningful value, indicating a bug in the code. But performing unconditional premature initialization of your variables you essentially kill that capability of the tool and sweep these bugs under the carpet.


This topic has already been discussed here:

http://www.velocityreviews.com/forums/t282290-how-to-initialize-a-char.html

It refers to C++, but it might be useful for you, too.


There are several good answers to this question, one of them has been accepted. I'm going to answer anyway in order to expand on practicalities.

Yes, it is good practice to initialize pointers to NULL, as well as set pointers to NULL after they are no longer needed (i.e. freed).

In either case, its very practical to be able to test a pointer prior to dereferencing it. Lets say you have a structure that looks like this:

struct foo {
    int counter;
    unsigned char ch;
    char *context;
};

You then write an application that spawns several threads, all of which operate on a single allocated foo structure (safely) through the use of mutual exclusion.

Thread A gets a lock on foo, increments counter and checks for a value in ch. It does not find one, so it does not allocate (or modify) context. Instead, it stores a value in ch so that thread B can do this work instead.

Thread B Sees that counter has been incremented, notes a value in ch but isn't sure if thread A has done anything with context. If context was initialized as NULL, thread B no longer has to care what thread A did, it knows context is safe to dereference (if not NULL) or allocate (if NULL) without leaking.

Thread B does its business, thread A reads its context, frees it, then re-initializes it to NULL.

The same reasoning applies to global variables, without the use of threads. Its good to be able to test them in various functions prior to dereferencing them (or attempting to allocate them thus causing a leak and undefined behavior in your program).

When it gets silly is when the scope of the pointer does not go beyond a single function. If you have a single function and can't keep track of the pointers within it, usually this means the function should be re-factored. However, there is nothing wrong with initializing a pointer in a single function, if only to keep uniform habits.

The only time I've ever seen an 'ugly' case of relying on an initialized pointer (before and after use) is in something like this:

void my_free(void **p)
{
    if (*p != NULL) {
        free(*p);
        *p = NULL;
    }
}

Not only is dereferencing a type punned pointer frowned upon on strict platforms, the above code makes free() even more dangerous, because callers will have some delusion of safety. You can't rely on a practice 'wholesale' unless you are sure every operation is in agreement.

Probably a lot more information than you actually wanted.


Preferred styles:

in C: char * c = NULL;

in C++: char * c = 0;


My rationale is that if you don't initialize with NULL, and then forget to initialize altogether, the kinds of bugs you will get in your code when dereferencing are much more difficult to trace due to the potential garbage held in memory at that point. On the other hand, if you do initialize to NULL, most of the time you will only get a segmentation fault, which is better, considering the alternative.


Initializing variables even when you don't need them initialized right away is a good practice. Usually, we initialize pointers to NULL, int to 0 and floats to 0.0 as a convention.

int* ptr = NULL;
int i = 0;
float r = 0.0;


It is always good to initialize pointer variables in C++ as shown below:

int *iPtr = nullptr;
char *cPtr = nullptr;

Because initializing as above will help in condition like below since nullptr is convertible to bool, else your code will end up throwing some compilation warnings or undefined behaviour:

if(iPtr){
   //then do something.
}

if(cPtr){
  //then do something.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜