Search code examples
cstrcpy

Whats the proper way to handle strcpy's return type


I created a program which at some point turned to be a buggy one and I can not find a good way to handle situations like in the following program:

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

int get_user_name( char *const dest, char *const src );
char *foo( char *variable ); /// foo() returns NULL

int main( void )
{
    char arr[256]      = { 0 };
    char buffer[ 256 ] = { 0 };
    char *const ptr    = foo( arr ); /// foo() returned NULL here

    if ( get_user_name( buffer, ptr ) == 0 ) /// get_user_name, should here return 0
    {
        printf("NULL returned from get_user_name()\n" );
        exit( EXIT_FAILURE );
    }else
    {
        printf( "Everithing is OK" );
    }
}

int get_user_name( char *const dest, char *const src )
{
    char *ret = strcpy( dest, src ); /// Here Segfault happens
    /// There is no return here because of above Segfault
    if ( ret == NULL )
    {
        return 0;
    }else
    {
        return 1;
    }
}

char *foo( char *variable )
{
    if ( strlen( variable) < 1 )
    {
        return NULL;    /// Here will return NULL because there is no Length
    }
    /// Some code here ...
    return variable;
}

Here is use a demo function which returns NULL to explain my problem. I was thinking to check src before past it to strcpy but I really cannot understand why strcpy returns dest without check if src is NULL or not.

Why does this happens because I see that strcpy manual say only about the return of dest and nothing if fails:

   RETURN VALUE
   The strcpy() and strncpy() functions return a pointer to the destination string dest.

Solution

  • You handle the situation by first checking the parameters are not null. For example:

    int get_user_name( char *dest, char *const src )
    {
        char *ret;
        if (dest==0 || src==0) return 0;
        strcpy( dest, src );
        return 1;
    }
    

    Note also that dest cannot be const because it is written to.