Curnelious
Curnelious

Reputation: 1

When do i have to add a null terminator?

I know that i C , you always have to add a null terminator \0 so that the processor knows when a word was ended .

But i get hard time to understand when you have to do it . so for example this code works for me without it :

  char connectcmd[50]={0};
  sprintf(connectcmd,"AT+CWJAP=\"%s\",\"%s\"",MYSSID,MYPASS);

How is that possible ? When do you really have to add them ?

Upvotes: 1

Views: 4095

Answers (3)

juanchopanza
juanchopanza

Reputation: 227538

sprintf writes a null terminated string connectcmd, regardless of its initial contents. This works as long as you don't try to write beyond the bounds of the buffer.

On top of that, when you say this:

char connectcmd[50]={0};

you initialize all 50 elements of connectcmd to zero, which is the value of the null-terminator \0. So it would be null-terminated even if you wrote characters to it manually, as long as you write less than 50 non-null characters.

Upvotes: 4

ameyCU
ameyCU

Reputation: 16607

sprintf always terminates it with null character , so no need to mannually add it.

From C99 standard -

7.21.6.6 The sprintf function

[...]A null character is written at the end of the characters written; it is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined.

Upvotes: 5

flogram_dev
flogram_dev

Reputation: 42858

for example this code works for me without it

It does not (work without it).

The string literal "AT+CWJAP=\"%s\",\"%s\"" has a null terminator at the end (like every string literal). sprintf copies that null terminator to connectcmd as well.

When do you really have to add them ?

When you're manually building a string, or using a library function whose documentation explicitly states that it isn't going to add a terminating null.

Upvotes: 3

Related Questions