Skip to content

Instantly share code, notes, and snippets.

@vaclavbohac
Created April 11, 2011 21:34
Show Gist options
  • Select an option

  • Save vaclavbohac/914401 to your computer and use it in GitHub Desktop.

Select an option

Save vaclavbohac/914401 to your computer and use it in GitHub Desktop.
Example of memory allocation in C.
// Example of memory allocation in C.
// For educational purposes only.
// Author: Vaclav Bohac
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int* number = malloc(sizeof(int));
*number = 3;
printf("Number is %d.\n", *number);
free(number);
char* foo = malloc(sizeof(char));
*foo = 'a';
printf("Foo is %c.\n", *foo);
free(foo);
char** bar = malloc(sizeof(char*));
*bar = "Hello, World!";
printf("%s\n", *bar);
free(bar);
int* array = malloc(4 * sizeof(int));
for (int i = 0; i < 4; i++) {
array[i] = i * i;
printf("%d. %d\n", i + 1, *(array + i));
}
free(array);
char** list = malloc(4 * sizeof(char*));
list[0] = "Live";
list[1] = "the Universe";
list[2] = "and";
list[3] = "Everything";
printf("%s, %s %s %s\n", list[0], list[1], list[2], list[3]);
free(list);
struct point {
int x, y;
};
struct point* p = malloc(sizeof(struct point));
p->x = 2;
p->y = 2;
printf("A (%d, %d)\n", p->x, p->y);
free(p);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment