1

I always get a Segmentation fault whenI use snprintf while `printf? works well.

Example:

int main(){
    while(1){
        uint8_t tmp = 3;
        printf("test %u", tmp); // <--- OUTPUT OK
        char * str = "            ";
        snprintf(str, 10, "test %u", tmp);  //  <--- SIGSEGV
    }
    return 0;
}

What is the problem?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
brazoayeye
  • 329
  • 1
  • 2
  • 14
  • 5
    `str` is pointer to string literal, which is read-only. Use `char str[13];` instead. [string literals](https://en.cppreference.com/w/c/language/string_literal), *String literals are not modifiable (and in fact may be placed in read-only memory such as .rodata). If a program attempts to modify the static array formed by a string literal, the behavior is undefined.* – rafix07 Dec 14 '21 at 08:44
  • @rafix07: thanks I missed that small difference – brazoayeye Dec 14 '21 at 08:55

0 Answers0