Linux下的C语言#strcpy/strncpy和memcpy


=Start=

缘由:

整理学习在进行Linux下C编程中碰到的一些知识点,方便以后进行参考。

正文:

参考解答:
void *memcpy(void *dest, const void *src, size_t n);    // copies n bytes from memory area src to memory area dest.
/* */
char *strcpy(char *dest, const char *src);              // copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest.
char *strncpy(char *dest, const char *src, size_t n);   // similar to strcpy(), except that at most n bytes of src are copied

&

int main()
{
    char *t = "Working on RedHat Linux";
    char *s;
    s = malloc (8000 * sizeof(char));
    memcpy(s, t, 7000);
    // memcpy(s, t, strlen(t) + 1);
    // memcpy(s, t, sizeof("Working on RedHat Linux"));
    printf("s = %s\nt = %s\n", s, t);
    free(s);
}
/*
以上代码出现段错误的主要原因在于 指针t 指向的区域大小小于 7000 字节,但是 memcpy() 还是会去读取 指针t 指向字符串内容之后的内容(可能是不可读区域),所以引发段错误。
建议在使用 memcpy() 时,源和目的都必须是可读的,同时最好也指定一个长度,防止越界。
*/

&

#include <stdio.h>
#include <string.h>
void main()
{
    char a[30] = "string(1)";
    char b[] = "string(2)";
    printf("sizeof('%s') = %d\n", a, sizeof(a));
    printf("sizeof('%s') = %d\n", b, sizeof(b));
    printf("strlen('%s') = %d\n", b, strlen(b));
    printf("before strcpy():%s\n", a);
    printf("after strcpy() :%s\n", strcpy(a, b));        // char *strcpy(char *dest,const char *src);
    // a[30] = "string(1)";    //warning: assignment makes integer from pointer without a cast
    strcpy(a, "string(1)");
    printf("after strncpy(a, b, 6) :%s\n", strncpy(a, b, 6));    // char *strncpy(char *dest,const char *src,size_t n);
    strcpy(a, "string(1)");
    printf("after strncpy(a, b, sizeof(b)) :%s\n", strncpy(a, b, sizeof(b)));
    strcpy(a, "string(1)");
    printf("after strncpy(a, b, strlen(b)+1) :%s\n", strncpy(a, b, strlen(b)+1));
}
参考链接:

http://man7.org/linux/man-pages/man3/memcpy.3.html

C函数之memcpy()函数用法
http://blog.csdn.net/tigerjibo/article/details/6841531

memcpy滥用导致的「segmentation fault」
https://stackoverflow.com/questions/8703948/memcpy-function-in-c

字符串拷贝/赋值 除了在初始化的时候直接赋值外,在后期处理上需要使用 strcpy/strncpy 而不能直接用 = 赋值
http://www.iteedu.com/os/linux/linuxprgm/linuxcfunctions/memstring/strncpy.php

http://man7.org/linux/man-pages/man3/strcpy.3.html
https://linux.die.net/man/3/strcpy

为什么该使用 strncpy 而不是 strcpy
https://stackoverflow.com/questions/1258550/why-should-you-use-strncpy-instead-of-strcpy

=END=

, ,

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注