Skip to content

Instantly share code, notes, and snippets.

@aaaronic
Last active April 8, 2020 20:05
Show Gist options
  • Save aaaronic/58c5748a5e10a225069300e28e7a4bee to your computer and use it in GitHub Desktop.
Save aaaronic/58c5748a5e10a225069300e28e7a4bee to your computer and use it in GitHub Desktop.
Dynamic memory tiny demo
// I rand this with gcc -std=c99 main.c && ./a.exe on Windows (cygwin)
// Mac/Linux people would probably prefer gcc -std=c99 main.c && ./a.out
#include <stdlib.h>
#include <stdio.h>
int main() {
printf("The size of an int is %d\n\n", sizeof(int));
int* ptr1 = malloc(1000*sizeof(*ptr1));
int* ptr2 = malloc(1000*sizeof(*ptr2));
printf("ptr1: %p\n", ptr1);
printf("ptr2: %p\n\n", ptr2);
printf("Before I set it: ptr1[0] = %d;\n", ptr1[0]);
ptr1[0] = 1525;
printf("ptr1[0] = %d;\n", ptr1[0]);
printf("\nReallocation ptr1 to 4000000 ints...\n");
void *temp = realloc(ptr1, 4000000*sizeof(*ptr1));
if (NULL == temp) { printf("couldn't realloc!"); }
else {
printf("Realloc succeeded!\n");
ptr1 = temp;
}
printf("ptr1: %p\n", ptr1);
printf("ptr1[0] = %d;\n", ptr1[0]);
printf("filling memory that I just allocated.\n");
for (int i=1; i< 4000000; i++) {
ptr1[i] = i;
}
// notice program memory in TaskManager or Activity Monitor went way up!
printf("\nPress enter to continue...\n");
fgetc(stdin);
printf("Resizing ptr1 back to 1000 members long.\n");
temp = realloc(ptr1, 1000*sizeof(*ptr1));
if (NULL == temp) { printf("couldn't realloc!"); }
else {
printf("Realloc succeeded!\n");
ptr1 = temp;
}
printf("ptr1: %p\n", ptr1);
printf("ptr1[0] = %d;\n", ptr1[0]);
// notice program memory in TaskManager or Activity Monitor went back down!
printf("\nPress enter to continue...\n");
fgetc(stdin);
printf("\nFreeing everything...\n");
free(ptr1);
free(ptr2);
printf("I don't own this: ptr1[0] = %d;\n", ptr1[0]);
ptr1[0] = 123;
printf("I changed it anyway: ptr1[0] = %d;\n", ptr1[0]);
}
$ gcc -std=c99 main.c && ./a.exe
The size of an int is 4
ptr1: 0x6000484c0
ptr2: 0x600049470
Before I set it: ptr1[0] = 0;
ptr1[0] = 1525;
Reallocation ptr1 to 4000000 ints...
Realloc succeeded!
ptr1: 0x6ffff0b0010
ptr1[0] = 1525;
filling memory that I just allocated.
Press enter to continue...
Resizing ptr1 back to 1000 members long.
Realloc succeeded!
ptr1: 0x60005a430
ptr1[0] = 1525;
Press enter to continue...
Freeing everything...
I don't own this: ptr1[0] = 1525;
I changed it anyway: ptr1[0] = 123;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment