j3141592653589793238
j3141592653589793238

Reputation: 1894

snprintf() only reads until new line character?

I'd like to send a message over a socket that looks like so: "USER anonymous\r\n". In order to create a formatted string instead of a constant string, I used snprintf(). Unfortunately, it does not seem to copy the newline character \n, but just the carriage return \r.

#define USERNAME_ANONYMOUS "anonymous"
[...]


// Inside a function.
int sz = snprintf(NULL, 0, "USER %s\r\n", USERNAME_ANONYMOUS);
char* username = NULL;
if ((username = calloc(sz + 1, sizeof(char))) == NULL) {
    perror("Could not allocate memory");
    return;
}
snprintf(username, sz, "USER %s\r\n", USERNAME_ANONYMOUS);
for (int i = 0; i <= sz; i++) {
    printf("%c  %d\n", username[i], username[i]);
}

The output:

U  85
S  83
E  69
R  82
   32
a  97
n  110
o  111
n  110
y  121
m  109
o  111
u  117
s  115
  13
  0
  0

Upvotes: 1

Views: 1535

Answers (2)

Luis Colorado
Luis Colorado

Reputation: 12688

Well, if you allocate a buffer of size sz + 1 then pass that buffer size to the second snprintf call, which is sz + 1 and not sz, which is the number you pass.

The second call to snprintf should read:

snprintf(username, sz + 1, "USER %s\r\n", USERNAME_ANONYMOUS);

or it will overwrite the last \n with the null terminator, because it has not enough space for the whole string you want to print.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409256

From this snprintf (and family) reference:

At most bufsz - 1 characters are written.

The size you provide must be including the terminator. You need to use sz + 1 to print the full string.

Upvotes: 4

Related Questions