为什么不检查在C中使用空指针?

0 c pointers

我正在为C中的程序编写一个简单的函数,它将打印一个用法语句并在调用时退出该程序.我希望有一个选项来传递一个字符串作为参数并显示它,但也没有传递任何内容并跳过该行.我的代码如下,主要功能如下:

#include <stdlib.h>
#include <stdio.h>

typedef struct opt_info
{
    char *start_path;                  /* Path to directory to start find in */
    int  name_flag;                            /* flag for the name argument */
    int  type_flag;                            /* flag for the type argument */
} opt_info;

/* function declarations */
int   process_args( opt_info *opts, int ac, char *av[] );
void  init_params( opt_info *opts );
void  print_usage();

int main ( int ac, char *av[] ) 
{
    opt_info opts;                            /* struct to store run options */
    process_args( &opts, ac, av );         /* handle the argument processing */

    printf("%s\n", opts.start_path);

    return 0;
}

int process_args( opt_info *opts, int ac, char* av[] )
{
    if ( ac < 2 )                                         /* not enough args */   
        print_usage();

    init_params( opts );                                  /* initialize opts */
    opts->start_path = av[1];                                  /* store path */

    return 0;
}

void init_params( opt_info *opts )
{
    opts->name_flag = opts->type_flag = 0;            /* set type flags to 0 */
}

void print_usage( char *message )
{
    if( message != NULL )           /* check for empty message string */
        printf( "%s\n", message );

    printf( "USAGE: pfind starting_path [-name filename-or-pattern] " );
    printf( "[-type {f|d|b|c|p|l|s}]\n" );

    exit( 1 );
}
Run Code Online (Sandbox Code Playgroud)

当我使用gcc编译并运行函数而不传递参数(即调用print_usage();)时,if语句仍然计算为true,并且在打印"USAGE:..."之前我得到一行打印出一些垃圾数据.

有没有关于C指针的东西我在这里缺少,有没有更好的方法来获得这个功能?

编辑:根据要求,更新的代码具有与我遇到问题的代码相同的函数调用.奇怪的是当我拿走一些不必要的代码(比如调用process_args())时,我最终得到了一个编译器警告,但是这对我的系统编译很好.

Cra*_*rks 6

默认情况下,指针不会初始化为NULL.实际上,在为其赋值之前,不会初始化C变量.

在为任何C变量赋值之前,它存在于未定义状态,通常称为"垃圾值".这就是已经发生在该内存位置的任何事情,通常不是0(或NULL).

message在调用print_usage()时正确初始化,只需将其作为参数传递:

print_usage(NULL);
Run Code Online (Sandbox Code Playgroud)