简体   繁体   English

使用memcpy从字符串复制到void指针的问题

[英]Problems using memcpy to copy from a string to void pointer

I want to use memcpy to copy a string to a void pointer (the reason I'm copying to a void pointer is that in my actual application I could be copying a variety of types, so I'm trying to be general), but using the bit of example code below I run into a problem: 我想使用memcpy将字符串复制到void指针(我正在复制到void指针的原因是在我的实际应用程序中我可以复制各种类型,所以我试图通用),但是使用下面的示例代码位我遇到了一个问题:

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

int main( void ){
  char *str1 = strdup("Hello");

  void *str2 = malloc(strlen(str1)+1);

  fprintf(stdout, "str1 = %s\n", str1);

  memcpy(str2, str1, strlen(str1)+1);

  fprintf(stderr, "str2 = %s\n", *(char **)str2);

  free(str1);

  fprintf(stderr, "str2 = %s\n", *(char **)str2);

  return 0;
}

In this example I get a Segmentation Fault when trying to print out str2 . 在这个例子中,我在尝试打印出str2时遇到了分段错误。 Does anyone know why this does not work? 有谁知道为什么这不起作用? Is it a problem with casting the void pointer to a char , or something more fundamental with memcpy ? 将void指针转换为char是一个问题,还是memcpy更基本的东西? However, if I change the memcpy line to memcpy(str2, &str1, strlen(str1)+1) I can print out str2 before freeing str1 , but after freeing str1 str2 has also disappeared. 但是,如果我将memcpy行更改为memcpy(str2, &str1, strlen(str1)+1)我可以在释放str1之前打印出str2 ,但在释放str1 str2也消失了。

I do know that it will all work if I declare str2 with char* rather than void* (and remove the casting in the output print statements), but I'd like to avoid that if possible. 我知道如果我用char*声明str2而不是void* (并删除输出print语句中的转换),它将全部工作,但我想尽可能避免这种情况。

Update : I've change the example code to avoid an initial memory leak. 更新 :我已更改示例代码以避免初始内存泄漏。

Your cast is wrong. 你的演员是错的。 You don't want *(char **) , you just want (char *) , and even that isn't really necessary. 你不想要*(char **) ,你只想要(char *) ,甚至那不是真的有必要。

Also, your initial malloc is nothing but a memory leak, strdup allocates its own memory. 此外,您的初始malloc只是内存泄漏, strdup分配自己的内存。

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

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