cyler
June 10, 2010, 2:36pm
1
I get this Valgrind error while using malloc but if I use calloc then there is no error.
I allocate 8 bytes for the string inside sprintf, 12 for the ip and 1 for the string terminator. This totals 21, so why is it talking about 20 bytes and 18 bytes ?
Partial code:
char ip[] = "80.80.80.80";
int buffer = 8 + strlen(ip); // 8 for headers fixed text
char *headers = malloc(buffer + 1);
sprintf(headers, " -r %s\r\n", ip);
send(foobar, headers, buffer, 0);
Your fixed-lenght text is only 6 characters, not 8. The substring "\r\n" is two bytes - carriage return and linefeed, not four bytes.
cyler
June 11, 2010, 6:01am
3
Yes, it seems gedit does not count the bytes correctly (and me neither). strlen states 6 bytes.
cyler:
I get this Valgrind error while using malloc but if I use calloc then there is no error.
I allocate 8 bytes for the string inside sprintf, 12 for the ip and 1 for the string terminator. This totals 21, so why is it talking about 20 bytes and 18 bytes ?
Valgrind is reporting the storage required correctly...
cyler:
Partial code:
char ip[] = "80.80.80.80";
int buffer = 8 + strlen(ip); // buffer=19 becoz strlen excludes the terminating null byte
char *headers = malloc(buffer + 1); // malloc allocates 20 bytes
sprintf(headers, " -r %s\r\n", ip); // this is 18 bytes becoz sprintf adds a null byte at the end
send(foobar, headers, buffer, 0);