strcpy和strncpy

当我们在使用strcpy()时,是否有考虑过当源字符串的空间大于目标字符串的空间会出现什么样的情况:以下我作了一个简单的案例:

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

int main() {
    char *obj="Hello World!";
    char dest[5]={0};
    
    
    strcpy(dest,obj);
    printf("%s\n",dest);

    return 0;
}

当用gcc编译执行后,出现了段错误.这显然是很危险的,所以libc中还有一种更为谨慎的字符串拷贝函数strncpy(),继续做一个案例:

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

int main() {
    char *obj="Hello World!";
    char dest[5]={0};

    strncpy(dest,obj,sizeof(dest)-1);
    printf("%s\n",dest);

    return 0;
}

编译执行后输出的结果是: hell也没有出现了段错误,所以当需要使用到字符串拷贝的时候,优先使用strncpy()是一种更不错的选择.这里有一个细节需要注意,需要留出1个单位的空间来存放'\0',所以在第三个参数我使用sizeof(dest)-1,这里如果不-1,则还是会出现段错误,因为字符串是以\0标志结束的,所以一定要留一个空间. 

猜你喜欢

转载自www.cnblogs.com/hzxz/p/11615430.html