|Dynamic Memory Allocation|
I'm working on my program to solve Sudoku puzzles again, and this time I'm using pointers. I just encountered a question about pointers on Quora that turned on my fingers and all this came out:
No, you cannot delete something that was statically declared in your source code. If you dynamically allocate a block of memory, you can assign the address of that block to a pointer variable. If you change the value of that pointer variable, it will no longer point to that block. If you haven’t saved that address somewhere, the block is effectively deleted because you won’t be able to access it because you don’t know where it is. If you delete the block of memory (using free or something similar), you shouldn’t be able to access that memory using your pointer. Depending on circumstances, if you haven’t mucked with the address stored in your pointer, you might still be able to access something, but it might not be yours anymore, or you might trigger a fault and the OS will kick you off.
Variables declared inside of functions are usually found on the stack, so the memory they use to store their values is dynamically allocated, so to speak. When the function is invoked, the space for your local variables is reserved, and when the function exits that space is reclaimed and merged with the unused space on the stack. It’s not really a problem because you can’t access those variables from outside the function.
You could dynamically allocate a variable, sort of. You could typedef (define) a structure, and then allocate space for a copy and assign that address to a pointer. You can now store stuff in this structure. If one of the fields in your structure is a pointer, you could allocate another block of memory and store the address in this pointer. Then if you free the first block, the one containing the structure, you will have lost both blocks because you will no longer have the address of the second block.