how to use memcpy to initialize a char pointer in struct

Xinke Yi Source

this is how I define struct.

struct urlFormat
{
      int port;
      char *host;
      char *path;
      int cat;
      char *status;
};

this is how I initialize strcut and allocate the space for the pointer.

struct urlFormat *res;
res = malloc(sizeof(struct urlFormat));

when I used memcpy() function, it reported segmentation fault.

char *ptr1 = (char *)url;
  int len = strlen(ptr1);
  memcpy(res->host, ptr1, len);

I don't know how to solve it.

cpointersstructmemcpy

Answers

answered 3 months ago John3136 #1

res->host is just a pointer (that is not pointing to anything yet).

Until res->host is pointing to some valid memory you can't memcpy to it.

You can either malloc some memory res->host = malloc(len + 1);(+1 for the 0 terminator and sizeof(char) is always 1 so omit it) or in this case just use res->host = strdup(ptr1);

comments powered by Disqus