简体   繁体   English

memcpy(C)分割错误

[英]segmentation fault with memcpy (C)

I encountered "segmentation fault" error when running the following code, but I am wondering why: 运行以下代码时遇到“分段错误”错误,但我想知道为什么:

int main()
{
char *str = "abcdefghijklmn";
void *str_v;

memcpy(str_v, str, 14);

printf("str_v is %s \n", (char *) str_v);
return 0;
}

Thanks for help. 感谢帮助。

void *str_v;

defines str_v to be of type void * , ie, it can store a pointer a variable of any type. str_v定义为void *类型,即它可以将一个指针存储为任何类型的变量。 However, you need memory space for the characters to be copied by memcpy from the source to the destination. 但是,您需要存储空间,以便memcpy将字符从源复制到目标。 Therefore, you need to allocate enough memory using malloc - 因此,您需要使用malloc分配足够的内存-

char *str_v = malloc(strlen(str) + 1);

strlen does not count the terminating null byte in the string pointed to by str . strlen不计算str指向的字符串中的终止空字节。 Therefore, you have to allocate one extra byte for the terminating null byte. 因此,您必须为终止的空字节分配一个额外的字节。

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

int main(void) {
    // a string literal is read-only so make str
    // const so attempting to change will cause
    // compiler error
    const char *str = "abcdefghijklmn";

    // allocate memory dynamically to the 
    // string pointed to by str. +1 is for the
    // terminating null byte since strlen does 
    // not count the null byte
    char *str_v = malloc(strlen(str) + 1);

    // malloc can fail if there is not enough
    // memory to allocate. handle it
    if(str_v == NULL) {
        printf("error in memory allocation\n");
        return 1;
    }

    // copy all bytes in the string pointed to
    // by str to the buffer pointed to str_v.
    // number of bytes to be copied is strlen(str) + 1
    // +1 for copying the terminating byte as well
    memcpy(str_v, str, strlen(str) + 1);

    // print the copied string. It need not be
    // cast to (char *) since str_v is already
    // of type (char *) 
    printf("str_v is %s \n", str_v);

    // free the dynamically allocated space 
    free(str_v);
    return 0;
}

您需要首先为str_v分配内存:

void *str_v = malloc(14);

You are using uninitialized pointer in memcpy(str_v, str, 14); 您正在memcpy(str_v, str, 14);中使用未初始化的指针memcpy(str_v, str, 14); , to fix it, you could add the following statements before it: ,要对其进行修复,可以在其前面添加以下语句:

str_v = malloc(14);
if (str_v == NULL) { /* malloc failed */ }

因为您尚未为str_v分配任何内存

You can just do 你可以做

char * str_v = strdup( str );

From http://linux.die.net/man/3/strdup : http://linux.die.net/man/3/strdup

#include <string.h>

char *strdup(const char *s);

The strdup() function returns a pointer to a new string
which is a duplicate of the string s. 
Memory for the new string is obtained with malloc(3),
and can be freed with free(3).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM