Created
November 10, 2015 07:49
-
-
Save bzdgn/9afa41d32a7f7a12ec20 to your computer and use it in GitHub Desktop.
Void Pointers & Malloc & Free Sample
This file contains 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 <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