Mair / esp32-course

Course on the ESP32 IDF
https://learnesp32.com
282 stars 122 forks source link

error: passing argument 1 to restrict-qualified parameter aliases with argument 3 [-Werror=restrict] #45

Open davidmoshal opened 3 years ago

davidmoshal commented 3 years ago

Exercise 5.1 Ubuntu 20.04

../main/main.c: In function 'exclaimIt':
../main/main.c:70:3: error: passing argument 1 to restrict-qualified parameter aliases with argument 3 [-Werror=restrict]
   sprintf(phrase, "%s!", phrase);
   ^~~~~~~
cc1: some warnings being treated as errors
ninja: build stopped: subcommand failed.
The terminal process "/bin/bash '--init-file', '/home/davem/esp/esp-idf/export.sh', '-i', '-c', 'cmake --build .'" terminated with exit code: 1.
davidmoshal commented 3 years ago

This works: strcat(phrase, "!"); though I would like to know what the above error means and how to avoid it. thanks for an EXCELLENT course, really enjoying it!

georgemichalis commented 3 years ago

The C library function int sprintf(char *str, const char *format, ...) sends formatted output to a string pointed to, by str.

Consider the following scenario. sprintf(phrase, "%s %s", phrase, phrase); What the final string will be on that? It may be "phrase phrase" or "phrase phrase phrase", or whatever because this is implementation dependent, and in general these kind of stuff are undefined behavior in C where anything could happen. You need an intermediate buffer to get it to work sprintf(buffer, "%s!", phrase);

On its own, on a traditional C you may not get this error but the actual definition on of sprintf on idf is sprintf, (char *__restrict, const char *__restrict, ...)

When we use restrict with a pointer ptr, it tells the compiler that ptr is the only way to access the object pointed by it and compiler doesn’t need to add any additional checks. Since accessing the "phrase" from 2 different points violates the above condition, result is undefined behavior and this is why you get the warning.