Proper way to initialize a string in C

后端 未结 11 1264
臣服心动
臣服心动 2021-02-01 08:23

I\'ve seen people\'s code as:

char *str = NULL;

and I\'ve seen this is as well,

char *str;

I\'m wonder, what

11条回答
  •  时光取名叫无心
    2021-02-01 09:23

    Because free() doesn't do anything if you pass it a NULL value you can simplify your program like this:

    char *str = NULL;
    
    if ( somethingorother() )
    {
        str = malloc ( 100 );
    
        if ( NULL == str )
            goto error;
    }
    

    ...

    error:
    
    cleanup();
    free ( str );
    

    If for some reason somethingorother() returns 0, if you haven't initialized str you will free some random address anywhere possibly causing a failure.

    I apologize for the use of goto, I know some finds it offensive. :)

提交回复
热议问题