I have the following code in which I'm trying to create a buffer of length 7 bytes and then put an integer in network byte order along with a char array in the buffer, I should not have the Null character at the end of my sprintf()
buffer so I'm using memcpy()
to just copy 7 bytes. However, I seem to be getting different buffers after memcpy()
.
Code:
int num = 1234;
char *dummy = "bla";
int dummy_len = strlen(dummy);
int buffer_len = sizeof(int) + dummy_len;
char *buffer = malloc(buffer_len);
char *temp_buf = malloc(buffer_len);
size_t len = buffer_len;
sprintf(temp_buf, "%d%s",htonl(num),dummy); //preparing the temp_buf
memmove(buffer, temp_buf, len);
printf("sizeof(temp_buf) = %d and sizeof(buffer) = %d\n",sizeof(temp_buf), sizeof(buffer));
printf("printing buffer = %s and temp_buf = %s\n", buffer,temp_buf);
I'm getting the following output:
sizeof(temp_buf) = 4 and sizeof(buffer) = 4
printing buffer = -771489 and temp_buf = -771489792bla
You don't need the sprintf, just copy the data directly.
int temp = htonl(num);
memmove(buffer, &temp, sizeof(temp));
memmove(buffer+sizeof(temp), dummy, strlen(dummy));