I am working with a collaboration on a big project. Due to our code's infrastructure, basically all functions must "return by reference":
void doSomething(TYPE &result) {
// do something to result
}
However, I am running into some Segmentation Errors when trying to use references to pointers. Especially when I try to clean up the memory, bad things happen. To try and understand the segfaults, I made a very simple test code. My first attempt compiled and ran without any errors:
int main() {
int* a;
delete a; // Seems to cause no problem!
}
Since this worked, I decided to try something similar with a reference to a pointer:
int main() {
int* a;
delete a; // Suddenly, this line is an "invalid delete".
int*& b = a;
}
Why does this suddenly segfault? Also, if a "proper way" exists to clean up the memory reserved by a pointer via a reference, what is it?
Some research notes:
I tried to find some answers here on StackOverflow. It should be safe to delete a NULL pointer according to Is it safe to delete a NULL pointer?... My pointer is totally uninitialized, so I might be doing something silly. However, in my big collaboration code, I would have to dig pretty deep to initialize this kind of pointer to NULL.
I also tried to learn about references to pointers in general. Another StackOverflow post suggested http://markgodwin.blogspot.co.il/2009/08/c-reference-to-pointer.html. That was a good read, but didn't solve my problem.
Thanks in advance!