Skip to content

Instantly share code, notes, and snippets.

@bzdgn
Created November 10, 2015 07:49
Show Gist options
  • Save bzdgn/9afa41d32a7f7a12ec20 to your computer and use it in GitHub Desktop.
Save bzdgn/9afa41d32a7f7a12ec20 to your computer and use it in GitHub Desktop.
Void Pointers & Malloc & Free Sample
#include <stdio.h>
#include <stdlib.h> /* for malloc function */
#include <string.h> /* memcpy */
int main()
{
void *p = malloc(4); /* 4 bytes requested */
if(!p)
{
printf("Memory allocation failed, program halted...\n");
return 1;
}
printf("****************************************************\n");
printf("size of int : %d\n", sizeof(int));
/* Use 4 byte for 1 integer */
*(int*)p = 1982;
printf("Content of void pointer : %d\n", *(int*)p);
printf("size of \"Lev\" string: %d\n", sizeof("LeV"));
/* Use 4 byte for 3 char and a null-terminator */
memcpy(p, "LeV", 4);
printf("Content of void pointer : %s\n", (char *)p);
printf("Content of void pointer : %c%c%c\n", *(char *)p, *(char *)(p+1), *(char *)(p+2));
printf("Content of void pointer : ");
int i; /* c89 standard compiler used */
void * pp = p;
for(i = 0; i<3; i++)
{
printf("%c", *(char *)pp++);
}
pp = 0;
printf("\n");
printf("****************************************************\n");
printf("\n");
if(p)
{
free(p);
p = 0;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment