Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Created August 22, 2024 21:19
Show Gist options
  • Save mortymacs/e4f4592d570219a57b9c355d32558058 to your computer and use it in GitHub Desktop.
Save mortymacs/e4f4592d570219a57b9c355d32558058 to your computer and use it in GitHub Desktop.
C - How to check nonnull parameter during compile time
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void action(char *a, char *b) __attribute__((nonnull(2)));
void action(char *a, char *b) {
if (a != NULL) {
printf("%s\n", a);
}
printf("%s\n", b);
}
int main() {
char *a = (char *)malloc(sizeof(char) + 1);
strcpy(a, "t");
action(a, a);
action(NULL, a);
action(a, NULL);
}
@mortymacs
Copy link
Author

  gcc b.c -Wall -Werror
b.c: In function ‘main’:
b.c:19:5: error: argument 2 null where non-null expected [-Werror=nonnull]
   19 |     action(a, NULL);
      |     ^~~~~~
b.c:7:6: note: in a call to function ‘action’ declared ‘nonnull’
    7 | void action(char *a, char *b) {
      |      ^~~~~~
cc1: all warnings being treated as errors

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment