c++ - Dealing with accessing NULL pointer - Stack Overflow
c - Accessing NULL pointers - Stack Overflow
Trying to understand NULL pointers
c - How to understand accessing NULL pointer when using in sizeof? - Stack Overflow
Dereferencing a null pointer will invoke undefined behavior. It may result in different things on different compilers, even more - different things may happen on the same compiler if compiled multiple times. There are no guarantees of the behavior at all.
What makes your process crash here is the OS stopping your program from fiddling with memory it does not have access to (at address 0). Windows will give you an "Access violation", Linux/Unix will give you a "segmentation fault".
Also, see Why are NULL pointers defined differently in C and C++? for a quote of what a null pointer is in the standard
You need to give the Pin some memory. Something like this:
Pin = new char[5]; // To make space for terminating `\0`;
for(...)
{
Pin[i] = '0' + i + 1;
}
Pin[4] = '\0'; // End of the string so we can use it as a string.
...
You should then use delete [] Pin; somewhere too (Typically in the destructor of the class, but depending on how it's used, it may be needed elsewhere, such as assignment operator, and you need to also write a copy-constructor, see Rule Of Three).
In proper C++, you should use std::string instead, and you could then do:
Class GSM
{
//...
private:
std::string Pin;
....
Pin = "0000";
for (uint8 i =0; i < 4; ++i)
{
Pin[i] += i+1;
}
Using std::string avoids most of the problems of allocating/deallocating memory, and "just works" when you copy, assign or destroy the class - because the std::string implementation and the compiler does the work for you.
You need to allocate a block of memory to store "1234". This memory block will be pointed by your Pin pointer.
You can try:
bool GSM::setDefaultValue()
{
lock();
Pin = new char[4];
for (uint8 i =0; i < 4; ++i)
{
Pin[i] = '0' + (i + 1);
}
unlock();
return true;
}
As you have allocated dynamicaly a memory block, you should always release it when you don't need it anymore. To do so, you should add a destructor to your class:
GSM::~GSM()
{
delete [] Pin;
}
Hello all again,
I have another stupid question here lol, so I'm trying to wrap my head around NULL. Im currently under the impression that NULL is a built in constant that has a value of zero, but what does that actually mean? When would it be appropriate to use null? If someone could explain it in layman's terms that would be super helpful!
The sizeof operator is evaluated at compile time. Its operand is not evaluated for side effects, so your program is safe. This is guaranteed by the standard 6.5.3.4/2 (emphasis mine):
If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
(Note that there is a special case of variable length arrays, in which case the evaluation takes place in run time, so code de-referencing an invalid pointer to a VLA inside sizeof would not be safe.)
As a side note, the correct format specifier for printf when printing the result of sizeof is %zu (the result of sizeof is type size_t).
Because sizeof(exp) is a compile time operator, and it does not evaluate expression exp at run-time.
As a result, there is no dereference of NULL pointer at run-time. You just have equivalent machine code of a constant in your printf statement in your final binary.
In C and C++, pointers are inherently unsafe, that is, when you dereference a pointer, it is your own responsibility to make sure it points somewhere valid; this is part of what "manual memory management" is about (as opposed to the automatic memory management schemes implemented in languages like Java, PHP, or the .NET runtime, which won't allow you to create invalid references without considerable effort).
A common solution that catches many errors is to set all pointers that don't point to anything as NULL (or, in correct C++, 0), and checking for that before accessing the pointer. Specifically, it is common practice to initialize all pointers to NULL (unless you already have something to point them at when you declare them), and set them to NULL when you delete or free() them (unless they go out of scope immediately after that). Example (in C, but also valid C++):
void fill_foo(int* foo) {
*foo = 23; // this will crash and burn if foo is NULL
}
A better version:
void fill_foo(int* foo) {
if (!foo) { // this is the NULL check
printf("This is wrong\n");
return;
}
*foo = 23;
}
Without the null check, passing a NULL pointer into this function will cause a segfault, and there is nothing you can do - the OS will simply kill your process and maybe core-dump or pop up a crash report dialog. With the null check in place, you can perform proper error handling and recover gracefully - correct the problem yourself, abort the current operation, write a log entry, notify the user, whatever is appropriate.
The other answers pretty much covered your exact question. A null check is made to be sure that the pointer you received actually points to a valid instance of a type (objects, primitives, etc).
I'm going to add my own piece of advice here, though. Avoid null checks. :) Null checks (and other forms of Defensive Programming) clutter code up, and actually make it more error prone than other error-handling techniques.
My favorite technique when it comes to object pointers is to use the Null Object pattern. That means returning a (pointer - or even better, reference to an) empty array or list instead of null, or returning an empty string ("") instead of null, or even the string "0" (or something equivalent to "nothing" in the context) where you expect it to be parsed to an integer.
As a bonus, here's a little something you might not have known about the null pointer, which was (first formally) implemented by C.A.R. Hoare for the Algol W language in 1965.
I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
I did a bit of googling and looking around on this reddit but I couldn't seem to find an answer to this problem. If I have a pointer that points to a null pointer and I try to access some part of that pointer with std::cout, then it won't do any other std::cout for the rest of the code. I have written a dummy program that demonstrates what is happening.
#include <iostream>
class Car {
public:
int year;
Car() {
year = 2021;
}
};
int main() {
Car lemon;
Car* pointer = nullptr;
lemon.year = 2000;
std::cout << lemon.year << "\n";
std::cout << pointer -> year << "\n";
std::cout << "I print when the above line is commented out\n";
return 0;
}In this code, the output will show lemon.year (2000) only once! It will execute the first std::cout but not the second or third. When I comment out the std::cout << pointer -> year << "\n"; THEN the third std::cout will print.
I'm not sure why this is happening. I've never really liked pointers but the problem I am working on sort of demands that I use pointers within my class (for anyone curious I am building a trie https://en.wikipedia.org/wiki/Trie)