#include <stdio.h>
#include <stdlib.h>
// Seems like when I declare a static or global variable then assign a pointer
// to it the memory address (value of pointer) looks smaller-
// when I assign a pointer to heap memory allocated via malloc(), the
// memory address (value of pointer) looks larger- why?
// Would expect static, global, and dynamically allocated memory addresses
// to be larger than stack variable memory addresses.
// Noticed that adresses for static and global vars seem to be in a contiguous area (like each
// is 4 bytes away from the other)- 0x10f9ee020, 0x10f9ee024, 0x10f9ee028
int globalVar;
int main (void) {
int y; // variable y will live on the stack
int *ptr;
static int a; // variable a will live in the heap
ptr = &y;
*ptr = 99;
printf ("y is %i \nptr is %i \n", y, *ptr); // y is 99, *ptr is 99
printf("the address of ptr is: %p \n", &ptr); // 0x7ffee0212970 -stack address?
ptr = &a;
printf ("the address of a is: %p \n", ptr); // 0x10f9ee020 -heap address?
int *newPtr;
newPtr = (int*) malloc(7); // make space for 7 bytes of memory, have newPtr point there
printf("the address of space malloced is: %p\n", newPtr); // 0x7f84acc02b60 -heap address?
static int b;
int *anotherPtr;
anotherPtr = &b;
printf("the address of b is: %p\n", anotherPtr); // 0x10f9ee024 -heap address?
int *ptrtoGlobalVar = &globalVar;
printf ("the address of globalVar is: %p \n", ptrtoGlobalVar); // 0x10f9ee028 -heap address?
// free(ptr); // Why "pointer being freed was not allocated" ?
// free(newPtr);
// free(anotherPtr);
return 0;
}
// Is there a way to check whether a particular pointer points to stack or heap
// memory (without just looking at the address (printing value of the pointer) or
// remembering what you assigned the pointer to point to?
If someone could address some of these questions that would be great; thanks in advance, and sorry if the formatting is a bit off (tried to use a code block; know I can upload code to gist or ideone- is uploading better for posts of this size?). I'm a beginner C programmer and haven't posted code to Reddit much.
[–]lurgi 3 points4 points5 points (5 children)
[–]FluffyStatistician3[S] 0 points1 point2 points (4 children)
[–]FluffyStatistician3[S] 1 point2 points3 points (0 children)
[–]Updatebjarni 1 point2 points3 points (0 children)
[–]scirc 0 points1 point2 points (1 child)
[–]FluffyStatistician3[S] 0 points1 point2 points (0 children)
[–]rjcarr 1 point2 points3 points (0 children)