【发布时间】:2018-11-24 17:29:39
【问题描述】:
我创建了一个程序,该程序在某些时候变成了一个错误的程序,我找不到处理以下程序中的情况的好方法:
#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;
}
这里使用一个返回NULL 的演示函数来解释我的问题。
我想在将src 传递给strcpy 之前先检查一下,但我真的不明白为什么strcpy 在不检查src 是否为NULL 的情况下返回dest。
为什么会发生这种情况,因为我看到 strcpy 手册只说 dest 的返回,如果失败则什么都没有:
RETURN VALUE
The strcpy() and strncpy() functions return a pointer to the destination string dest.
【问题讨论】:
-
但我真的不明白为什么 strcpy 在不检查 src 是否为 NULL 的情况下返回 dest。 - 因为它在标准中说它需要一个 c 字符串,而不是一个
NULL。而且我敢打赌strcpy()大多数时候不会返回任何东西,只会立即崩溃。 -
strcpy导致程序中止,因为其中一个参数为空。打电话前检查。 -
@Swordfish 我已经准备好指出问题中的段错误。我也知道标准是怎么说的。期待一些字符串,并依赖于没有检查就没有 NULL ,从我的角度来看,它并没有使它成为最好的功能。我知道作为
c程序员,我需要对照NULL检查所有内容,但这不是我的问题。