Created
May 21, 2025 15:15
-
-
Save tommie/5f8024c96a035e5e5adef8f4fb9e52fa to your computer and use it in GitHub Desktop.
C const behavior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
q.c: In function ‘main’: | |
q.c:6:10: error: assignment of read-only location ‘*a’ | |
6 | a[0] = 'H'; | |
| ^ | |
q.c:7:10: warning: passing argument 1 of ‘free’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] | |
7 | free(a); | |
| ^ | |
In file included from q.c:1: | |
/usr/include/stdlib.h:687:25: note: expected ‘void *’ but argument is of type ‘const char *’ | |
687 | extern void free (void *__ptr) __THROW; | |
| ~~~~~~^~~~~ | |
q.c:12:10: error: assignment of read-only location ‘*a’ | |
12 | a[0] = 'H'; | |
| ^ | |
q.c:13:10: warning: passing argument 1 of ‘free’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers] | |
13 | free(a); | |
| ^ | |
/usr/include/stdlib.h:687:25: note: expected ‘void *’ but argument is of type ‘const char *’ | |
687 | extern void free (void *__ptr) __THROW; | |
| ~~~~~~^~~~~ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
int main() { | |
{ | |
const char *a = malloc(4); | |
a[0] = 'H'; | |
free(a); | |
} | |
{ | |
char const *a = malloc(4); | |
a[0] = 'H'; | |
free(a); | |
} | |
{ | |
char * const a = malloc(4); | |
a[0] = 'H'; | |
free(a); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment