2

I have read many suggested questions, but still cannot find out the answer. I know the content in buffer is a NULL terminated char array, and I want to copy it into a dynamic allocated char array. However, I kept getting segmentation fault from the strcpy function. Thanks for any help.

void myFunction()
{
    char buffer[200];

    // buffer was filled by recvfrom correctly, and can be printed out with printf()
    char *message = malloc(200);

    strcpy(message, buffer[1]);
}

////////////////

ok, so i tried strcpy(message, &buffer[1]); strcpy(message, buffer); but nothing worked!!

5
  • 5
    crank up the warning level of your compiler and mind the warnings! Commented May 31, 2011 at 22:51
  • 3
    The second argument of strcpy() should also be a [const] char *, the buffer. It is currently the second item of the buffer, a char. Commented May 31, 2011 at 22:51
  • so should it be strcpy(message, &buffer[1])? Commented May 31, 2011 at 22:56
  • 1
    It is more idiomatic to write "strcpy( message, buffer + 1 )" Commented Jun 1, 2011 at 4:53
  • Your segfault is being caused by something different now. Not all segfaults are created equal. I updated the answer to include a terminating null byte in your buffer (the most likely candidate for what's causing your program to crash). Paste a larger snippet if you want more help or suggestions. Commented Jun 1, 2011 at 20:37

2 Answers 2

2

This works for me. Is it possible that your buffer is not null-terminated?

char buffer[200];
buffer[0] = 'h';
buffer[1] = 'e';
buffer[2] = 'l';
buffer[3] = 'l';
buffer[4] = 'o';
buffer[5] = '\0';

// buffer was filled by recvfrom correctly, and can be printed out with printf()
char *message = (char *)malloc(200);
strcpy(message, buffer);
Sign up to request clarification or add additional context in comments.

1 Comment

I could do printf("message is: %s", buffer); and it correctly printed out the message I sent using sendto. I am sure buffer contains the right c string
1

Your invocation of strcpy(3) is incorrect. Change it to the following:

    buffer[199] = '\0';
    strcpy(message, &buffer[1]);

strcpy(3) has the following signature:

 char *
 stpcpy(char *s1, const char *s2);

You passed in:

 char *stpcpy(char *s1, const char s2); /* won't work */

I would suggest using memcpy(3) instead of strcpy(3) since strcpy(3) relies on a null character to terminate the string.

Comments

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.