Created
June 18, 2013 03:11
-
-
Save Justasic/5802416 to your computer and use it in GitHub Desktop.
I used this to teach @lordofsraam how pointers work and how you can use them to store more than one value in memory (which is what every C string does but this is slightly different)
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 <new> | |
#include <cstring> | |
#include <stdlib.h> | |
#include <iostream> | |
#include <cstdio> | |
#include <malloc.h> | |
int main(int argc, char **argv) | |
{ | |
size_t *ptr = (size_t*) malloc(11);//malloc(3 + sizeof(size_t)); | |
printf("Malloc()'d pointer at: %p\n", ptr); | |
size_t blah = 11; | |
*ptr = blah; | |
printf("Ptr: %p\n", ptr); | |
printf("Val: %ld\n", *ptr); | |
printf("Changing memory space\n"); | |
ptr++; | |
char *str = (char*)ptr; | |
*str = 'H'; | |
str++; | |
*str = 'i'; | |
str++; | |
*str = 0; | |
//strcpy((char*)ptr, "Hi"); | |
printf("Val: %s\n", (char*)ptr); | |
printf("Ptr: %p\n", ptr); | |
ptr--; | |
printf("Reverting to original memory context\n"); | |
printf("Ptr: %p\n", ptr); | |
printf("Val: %ld\n", *ptr); | |
printf("Free()'d pointer at: %p\n", ptr); | |
free(ptr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment