Domanda

I'm reading an input string from the user with scanf().

I want to check if this string is NULL (\0) or not.

Here is my code:

#include<stdio.h>

char *argument; // argument for mycat
scanf("%s", &argument);

if(fork()==0)       // at child
{
    printf("Child process: about to execute \"mycat %s\"\n", &argument);
    fflush(stdout);
    if(strcmp(argument, "") == 0) // <-- Here is the problem
    {

        execlp("mycat", "mycat", &argument, NULL);      // execute child process
    }
    execlp("mycat","mycat", NULL);
}

I'm compiling with g++ compiler on Red Hat 6.1

Edit: The problem is that I'm not able to dereference argument either for the if statement or even for use with strlen().

È stato utile?

Soluzione

NULL and \0 are not the same thing, though they both evaluate to zero. NULL is a pointer zero, i.e. it's what we use for a null pointer. \0 is the character with ASCII number zero, otherwise known as NUL (one 'L'), i.e. is a char with value 0.

There is an important difference between a char * being NULL (i.e. there not being a string in memory at all), or the string being empty (i.e. only containing one char which is \0 otherwise known as NUL).

To test for the first:

if (!string)

or if you like to be more verbose:

if (string == NULL)

To test for the second:

if (!string[0])

or if you like to be more verbose:

if (string[0] == 0)

Obviously if you need to test for both, test for the first then the second, as the second would dereference a null pointer if string was NULL.

Altri suggerimenti

To answer the question:

Check scanf()'s return value to test whether the operation succeeded, read in something.

For your example it would return 0 if nothing was read, or EOF if there was nothing to read from or an error occured.


However there are issues with the example code:

1st issue:

char *argument; // argument for mycat

is just a pointer pointing to "somewhere/nowhere". Reading an uninitalised variable invokes undefined behaviour, copying data to "nowhere" also invokes undefined behaviour.

To fix this allocate some memory to it by for example doing:

char * argument = malloc(42); /* Allocate 41+1 bytes, that is room for a C-"string" 
                                 being 41 characters long. */
strcpy(argument, ""); /* Initalise it to an emtpy string. */

2nd issue:

scanf("%s", &argument);

tries to scan data to the address of argument not where it is pointing to (if it were).

To fix this do

scanf("%s", argument);

or even better, also tell scanf() the size if the buffer to read into, so it won't overflow it. SO assuming the above initialisation, this would be:

scanf("%41s", argument); /* Read one less then there is room, as the 42nd char is used to hold the '0'-terminator. */
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top