簡體   English   中英

您如何強制大小限制以防止格式截斷?

[英]How do you force a size limit to prevent format truncation?

submission.c:112:32: error: '%02d' directive output may be truncated writing between 2 and 3 bytes into a
region of size between 0 and 2 [-Werror=format-truncation=]
 snprintf(strTime, 5, "%02d:%02d", minFormed, secFormed);
                            ^~~~
submission.c:112:26: note: directive argument in the range [-59, 59]     snprintf(strTime, 5, "%02d:%02d", minFormed, secFormed);
                      ^~~~~~~~~~~
submission.c:112:5: note: 'snprintf' output between 6 and 9 bytes into a destination of size 5
 snprintf(strTime, 5, "%02d:%02d", minFormed, secFormed);
 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我有2個變量minFormedsecFormed ,它們都是整數。

通過這種方式,我不相信它們每個都可能超過2個字節。 計時器格式應為“ 00:00”,即5個字節。 我如何將secFormed部分強制為2個字節?

編輯:對不起,來晚了,忘了顯示更多代碼

char * getCurrentTime (void) {
    double time = ( overflow_counter * 256.0 + TCNT0 ) * PRESCALE  / FREQ;
    int timePassed = (int)(floor(time));
    int secFormed = timePassed % 60;
    int minFormed = timePassed / 60;
    char strTime[5];
    snprintf(strTime, 5, "%02d:%02d", minFormed, secFormed);
    return strTime;
}

計時器實際上不應超過99:59,因為它是用於可以在幾分鍾內玩的游戲,因此可以實現某種時間限制。

編輯:將字符串緩沖區更改為6大小后出錯

submission.c:109:32: error: '%02d' directive output may be truncated writing between 2 and 3 bytes into a
region of size between 1 and 3 [-Werror=format-truncation=]
 snprintf(strTime, 6, "%02d:%02d", minFormed, secFormed);
                            ^~~~submission.c:109:26: note: directive argument in the range [-59, 59]     snprintf(strTime, 6, "%02d:%02d", minFormed, secFormed);                          ^~~~~~~~~~~
submission.c:109:5: note: 'snprintf' output between 6 and 9 bytes into a destination of size 6
 snprintf(strTime, 6, "%02d:%02d", minFormed, secFormed);
 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我只是在這里猜測 ,因為您沒有提供最小,完整和可驗證的示例

似乎您正在將長度5作為緩沖區大小的參數傳遞。 那就是包括字符串終止符的緩沖區大小。

從此snprintf (和系列)參考中

bufsz最多bufsz - 1可以寫入bufsz - 1字符,加上空終止符

您的字符串是六個字符(包括終止符),因此您需要至少六個字符的緩沖區,並告訴snprintf該大小。

哦,關於范圍的注釋是因為您使用帶符號整數,所以范圍也包括負數,這意味着額外的空間。 您可能應該改用unsigned int ,格式為"%02u"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM