Observing the strcpy declaration
char * strcpy ( char * destination, const char * source );
We notice that it copies the chars from source and store them in destination. But note that it's not specified the length of destination. So it may cause problems if the destination is:
- Smaller than the source (Overflow)
- Not allocated to some space in the memory (Segmentation Fault)
It's because strcpy function tries to copy char by char until it gets to the end of the 'string'. See how it should look like:
char *strcpy(char *destination , const char *source ){
char *saved = destination;
while (*source){ // while is not NULL
*destination++ = *source++; // Pointer operation
}
*destination = 0; // last position is set to 0 (which is NULL, end of string)
return saved;
}
So when you perform strcpy(mess.buffer,"hello")
you can't actually find mess.buffer++
because there's no next memory block since you did not allocated sequential memory. Thus, Segmentation Fault happens.
Finally, you could do:
/* Note that "hello" occupies 6 char spaces: 'h', 'e', 'l', 'l', 'o', '\0' */
int mySize = 10;
mess.buffer = malloc(mySize * sizeof(char));
strcpy(mess.buffer, "hello") // 10 > 6 so OK