Skip to content

Instantly share code, notes, and snippets.

@dylanchapell
Created December 16, 2023 20:27
Show Gist options
  • Save dylanchapell/0f8ddd214764a95ec211f6d5e4adc764 to your computer and use it in GitHub Desktop.
Save dylanchapell/0f8ddd214764a95ec211f6d5e4adc764 to your computer and use it in GitHub Desktop.
What happens on malloc0? Does it return NULL or a valid pointer? Depends on the system. If it returns NULL, this program segfaults on the assert.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main() {
void* myemptyptr = malloc(0);
void* myfullptr = malloc(10);
assert(myemptyptr);
printf("Empty pointer: %p 10byte Pointer: %p\n", myemptyptr, myfullptr);
free(myemptyptr);
free(myfullptr);
for (int i=0; i<1000; i++) {
void* newptr = malloc(0);
void* newcptr = calloc(0, sizeof(char));
assert(newptr);
assert(newcptr);
free(newptr);
free(newcptr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment