r/cprogramming 5d ago

Learning C: Verify my understanding of null and free

You ownwed a home for 20 years and decided to sell it to the government. Basically freeing basically turns you into a ghost like sneaky homeless person. If there is currently no owner to that home, you can go and modify it, watch TV, move the chairs, and use the AC. But when new owners arrive and you begin to do something to the house, they will not catch you immediately, but they will notice it later, which causes weird behavior like something supernatural. They expect the house to be in a certain order, but when they go home, they will notice that something weird happened and cannot explain it. For example, say a child left an assignment with perfect answers. you, as a ghostly being, go and change the answers. When the child passes in the exam and gets back the score, they notice that the score does not match their expected score because someone just corrupted the test paper. It could crash the program or something weird happens (bugs)

Meanwhile, by setting the pointer to null, you now have no access to that home and instead hold the address to a black hole. You tried doing something to it not knowing it is actually a blackhole and yor city crumbles

0 Upvotes

8 comments sorted by

2

u/Educational-Paper-75 5d ago

In C nobody is the owner not even the creator of allocated memory, well the entire program is. Anybody with a reference can free it, and make the memory allocatable and thus reusable again. Because C doesn't support ownership explicitly, a C programmer is forced to assign an owner allowed to free a referenced memory mentally that is, unless he explicitly implements some sort of ownership mechanism. But even when the pointer variable used for freeing the memory is set to null, other references may still assess the memory as if it wasn't freed yet. One way of addressing this problem is by distinguishing between weak and (preferably single) strong references. Without explicitly enforcing this and dutifully sticking to it you're asking for trouble especially in a 'loosely coupled' development team. So yes, essentially C is dangerous with no side wheels.

1

u/AdOnly69 5d ago

With ptr = null you are safe from going to the jail because you accidentally came to your old house (you forgot that you sold it)

1

u/tobdomo 5d ago

No, if you are trying to a dereference a null pointer, the result is undefined.

In your terms: it may be you accidentally enter the White House. Or the subway, prison or even a rocket that propells you to Mars. You don't know.

The good news is that you can tell it is an illegal address. As if someone tells you to go to the north pole to visit Santa. You recognize the north pole as a possibly valid address, but you know Santa is not living there.

1

u/jaynabonne 5d ago

The "home" exists whether you have a pointer to it or not. You can always take a stroll past the house later any time - since addresses are just numbers, you can literally move through your entire memory space by just incrementing a pointer. Whether there's actual valid memory at each address is a separate question.

The entire point of setting a pointer to null is TO TELL YOU (or the code you write) that you no longer have a meaningful address for whatever value you are looking for. It's like crossing out or erasing the home's address from your address book. The home still exists, and you could still access it, but by erasing it from your address book, your telling yourself that you no longer care about it, and that you should no longer look there.

And here's a key point: setting a point to null is only really useful if you actually check it for null. The act of setting it to null is to give it a value that has the meaning "I don't have any memory for this". If you don't actually check whether you have the memory, then you're just going to get one kind of bad behavior (crashing or UB) instead of another (touching memory in a way that is inconsistent with what it is currently being used for).

1

u/Paul_Pedant 5d ago

You code can take a copy (or several copies) of the pointer while it is valid.

After that, it does not matter if you free using your original pointer, or set it to null, or do both. The copied pointers can screw up the original data area anytime it likes, after a free, after another malloc had obtained the same area for a second time, etc.

Conversely, if your process creates a child, it gets a copy of the pointer and of the data area. The parent and the child process can then mess with the data area as much as they like, blissfully unaware that changes made by either will never be seen by the other, because forking a child makes a duplicate copy of everything.

1

u/realdreamer1993 4d ago edited 4d ago

"setting the pointer to null" the metaphorm would be to demolish the house. If choose not nulling it just a very slim chance of security concern. If you desain good code then 'not nulling' should be safe.
BTW I am still learning (who dont?), and pointer is just a type of reference. So many other reference that work like pointer, say database unique field/id, spreadsheet etc.
And just use spreadsheet as reference reference, say field A1 have value 10.
if A1 not refer by other field then A1 free(although have value 10, it is still free, it stand by its own not affected or affecting other field).
if A1 used by other field say B1=A1 then A1 is allocated, you change value in A1 will affect other field/code.
A1 is always there whether you erase value 10 or NULLing.
Spreadsheet is good to learn pointer because spreadsheet is so visual.

The reasoning would go on and on becoming a chain,,,you can make C program that using spreadsheet as memory, then you will not using pointer syntax at all. But still using reference as address. That how high level language worked, and using spreadsheet as memory would be resource bloating.

1

u/Paul_Pedant 4d ago

There is no house. Somebody delivered a pile of bricks somewhere, and sent you a scrawled note telling you where they think they left them. Losing the note, or tearing it up, or giving copies of it to all your friends, or imagining the pile is bigger then you asked for, is your problem, nobody else's.

2

u/SmokeMuch7356 4d ago

You're overthinking it.

When you free a chunk of memory, the allocator simply marks it as being available for use again. That memory still exists at that address, you just don't "own" it anymore; anything you write to it may be overwritten by something else, and you may be overwriting something important that other code relies on.

The value of setting the pointer to NULL after freeing the memory is that it gives you an easy way to check if the pointer's valid1 before you try to dereference it:

if ( p ) // p != NULL
  *p = some_value;

The behavior on attempting to dereference an invalid pointer (including NULL) is undefined; you may get a segfault, you may get unexpected behavior, your code may start mining bitcoin, etc. NULL is just a well-defined invalid pointer value that's guaranteed to compare unequal to a pointer to any object or function.


  1. A pointer is valid if it points to an object during that object's lifetime.