문제

 int main()
 {
     char buf1[100], buf[100]="ddl";

     sprintf(buf1, "log_name = '%.*s'", buf);
  }

The above program is crashing. I am not able to understand why is this crashing. As far as I know before the character makes printf to skip the format code and assign buf to next format code. But here what is the significance of?

도움이 되었습니까?

해결책

The format specifier "%.*s" requires the number of characters to be written to be specified:

sprintf(buf1, "log_name = '%.*s'", 3, buf); /* For example */
                                /* ^ */

In the posted code only buf is provided so there are missing arguments, which is undefined behaviour (in this case a crash).

Note, in this case, "%s" would serve just as well as buf is null terminated (no requirment for a length unless all characters in buf must not be copied).

다른 팁

You can see the effect of this as follows .

int main()
{   
printf("%.*s",13,"stackoverflow rocks");
}

which will give you only stackoverflow .

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top