سؤال

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:

#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. 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? 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.

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.

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.

Also, your initial malloc is nothing but a memory leak, strdup allocates its own memory.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top