Question

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
Was it helpful?

Solution

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

OTHER TIPS

It is incoherent to use sizeof(int) and then sprintf(...,"%d... Not all 4-byte integers print with 4 digits in decimal.

In particular, htonl(num) is likely not to print with a 4-digit decimal representation. Therefore, sprintf() overflows the buffer temp_buf.

You should use something like:

uint32_t n = htonl(num);
memcpy(temp_buf, &n, sizeof(n));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top