0

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.

3

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Comment now deleted but OP asked how to copy part of a string: You need to allocate space for as much as you want to copy and then copy that amount. strncpy would do it or you could use strdup and just put a 0 in the string after the last character that you want. This wastes a bit of memory but is completely legal. It all depends on what you really want to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.