Null pointers and New Ints | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Null pointers and New Ints

Whats the point of making a null pointer? Wouldnt a pointer with a deleted address just be a dangling pointer that can be reassigned and not Null? also it says Null has a value of zero but doesnt Null mean no value? so 0 would still be a value. Whats the difference between declaring an int and making new int? one is in the stack and the other a heap? how do you know how much memory you have in a stack before you use a heap?

12th Apr 2017, 4:18 AM
Noah
Noah - avatar
1 Answer
+ 2
Firstly, for some memory management functions, it's far easier to use a NULL pointer (a conventional value used to signal reference to an invalid object) than using a non-valid one with some rubbish value. For example, the C-function "realloc", that allows resizing a portion of allocated memory, requires a valid pointer in order to perform the resize. Using a rubbish, non-valid value potentially throws a Segment Violation (using memory that is not yours), and depending on the program and the environment, it can lead from a program stop to a crash. Secondly, the stack and the heap are different portions of memory that your program can use internally. For declared variables, a stack is useful as it can store them depending on the current scope. Recursive functions are a good example: for each nesting level, its variables are stacked to prevent losing them. Once you hit the base case, they are popped from the stack and combined in a certain way so you get a meaningful result. The stack has a certain size depending on the compiler you use, and it can be changed when you compile your program. The heap, on the other hand, allocates space for variables that exist regardless of the scope. You can access them even at the deepest levels of a recursion, and modifying them will be visible for all the other levels, once they get the chance to do so. The only way for them to disappear is by explicitly deallocating them. The heap has also a compiler-defined size that may be changed. This (highly technical) page explains this in detail: https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/stack.html
12th Apr 2017, 5:09 AM
Felipe BF