r/shittyprogramming • from The Cloud™ • Feb 16 '15

I am a null pointer. AMA

457 Upvotes

127 comments sorted by

152

u/deegeese Feb 16 '15 edited Jun 23 '23

[ Deleted to protest Reddit API changes ]

88

u/tmewett from The Cloud™ Feb 16 '15

Sure, my contact is /dev/zero

42

u/belikralj Feb 17 '15

ln -s /dev/zero /dev/hero

46

u/[deleted] Feb 17 '15

Well, it's only symbolic, but it means something to me.

5

u/partyboy690 Feb 17 '15

You made me blow air out my nose slightly, have an upvote :)

112

u/atuno123 Feb 16 '15

All AMAs require proof.

290

u/tmewett from The Cloud™ Feb 16 '15
#include <stddef.h>

32

u/diesal11 Feb 16 '15 edited Dec 02 '16

Fuck. Man. I haven't laughed that hard in a while! If I could i would guild you!

6

u/orlandodad Feb 16 '15

Please explain?

16

u/karmapopsicle Feb 16 '15

Looks like he was autocorrected. What he meant to say was "If I could I would gild you!" as in gift reddit gold to OP.

2

u/orlandodad Feb 17 '15

I was going for the explanation of why its funny not the gilding aspect of it.

0

u/[deleted] Feb 17 '15

[deleted]

24

u/karmapopsicle Feb 17 '15

It's OK, I made an exception.

8

u/[deleted] Feb 17 '15

stddef.h contains the macro definition of null

1

u/diesal11 Feb 17 '15

Autocorrect hit me hard.

1

u/flarn2006 Feb 17 '15

What did it say originally?

7

u/diesal11 Feb 17 '15 edited Dec 02 '16

Just typos. "If I could i would guild you!" i think

93

u/[deleted] Feb 16 '15

I'll cast you all night baby.

195

u/tmewett from The Cloud™ Feb 16 '15

well, that's (char *)ming.

79

u/MachinaExDeo Feb 16 '15

All night (long *) baby.

32

u/[deleted] Feb 16 '15

I could definitely get into this.

29

u/MachinaExDeo Feb 16 '15
error: cast from 'void*' to 'int' loses precision

26

u/[deleted] Feb 16 '15
Java.awt.NullPointerException: The_Dragonn_29.getCareLevel() returned null.

36

u/iloveportalz0r Feb 17 '15

>Java.awt.NullPointerException

>not java.lang.NullPointerException

java.u.wot.M8

15

u/[deleted] Feb 17 '15

Sorry, didn't feel like opening Eclipse and nullpointer something.

24

u/iloveportalz0r Feb 17 '15

>not memorizing essential Java details

9

u/[deleted] Feb 17 '15

It's an error message.

For a nullpointer.

Do you really need to memorize the exact location of the Java error type?

→ More replies (0)

36

u/5thWall Feb 16 '15

Are you really living up to your potential? Are your parents proud of what you've become?

86

u/tmewett from The Cloud™ Feb 16 '15

wow, downcoded. it's not what you point to that counts.

14

u/fuzz3289 Feb 16 '15

I dont believe you, this post evaluates to False.

57

u/tmewett from The Cloud™ Feb 16 '15

so does your face

26

u/macumbamacaca Feb 16 '15

Why are you pointing instead of referring?

78

u/tmewett from The Cloud™ Feb 16 '15

if i told you, i'd have to SIGSEGV you

8

u/ponyoink Feb 16 '15

Where is it?

14

u/tmewett from The Cloud™ Feb 16 '15

definitively nowhere

8

u/tiajuanat Feb 16 '15

What exactly do you do here?

37

u/tmewett from The Cloud™ Feb 16 '15

You know that feeling when you think someone is watching you? That's a pointer staring at you from another process.

56

u/[deleted] Feb 16 '15

How does it feel when your dad calls you a billion-dollar mistake?

47

u/worklederp Feb 16 '15

He should shut his Hoare mouth.

19

u/Nialsh Feb 16 '15

How could null be a mistake? We JS devs like null so much that we use undefined too!

4

u/[deleted] Feb 16 '15

Yep, use it all the time for flexible function parameters.

3

u/immibis Feb 18 '15

VBA has 4 different kinds! Empty, Nothing, Null and Missing (although there isn't a constant called Missing AFAIK)

2

u/[deleted] Feb 17 '15

Why use null, when you can use empty string...

5

u/lukeomatik Feb 16 '15

But why? I seriously dont understand why a NULL mechanic should be a billion-dollar mistake.

11

u/Bratmon Feb 17 '15 edited Feb 17 '15

Because, really, any language with strong typing should always have been using optional values instead of null pointers. The former was always a better solution, and had Hoare not set a precedent of them being available, they might not be expected in modern languages, forcing people to use optional.

3

u/[deleted] Feb 17 '15

Because when you have a variable "Foo foo" in your program, and you want to do something with it, you almost always have to handle the cases "foo == null" and "foo != null" differently, but the overwhelming majority of programming languages do nothing to encourage you to handle both cases - e.g. there's no compiler warning when you say "foo.bar()".

I guess you could say that the billion-dollar mistake was to introduce null without introducing non-nullable reference types and without making it a good compiler development practice to emit warnings when you dereference something without checking if it's null (and both points are moot in a dynamically typed language, so in those nulls are just plain evil :) )

2

u/autowikibot Feb 16 '15

Tony Hoare:


Sir Charles Antony Richard Hoare FRS FREng (born 11 January 1934), commonly known as Tony Hoare or C. A. R. Hoare, is a British computer scientist. He developed the sorting algorithm quicksort in 1959/1960. He also developed Hoare logic for verifying program correctness, and the formal language Communicating Sequential Processes (CSP) to specify the interactions of concurrent processes and the inspiration for the [occam programming language](https://en.wikipedia.org/wiki/Occam_(programming_language)).

====

Image i


Interesting: List of London's Burning episodes (series ^6) | He ^Jifeng | List of London's Burning episodes (series ^1) | Eric ^Hehner

Parent commenter can toggle ^NSFW or ^delete. Will also delete on comment score of -1 or less. | FAQs | ^Mods | Magic ^Words

40

u/w3woody Feb 16 '15

NULL, nil or null?

9

u/Imxset21 Feb 16 '15

None is sort of like NULL?

1

u/[deleted] Feb 17 '15

NULL*

1

u/jP_wanN Feb 17 '15

((void*)0)

1

u/[deleted] Feb 17 '15

-1

1

u/[deleted] Feb 18 '15

42

u/whelks_chance Feb 16 '15

I hate you. That is all.

18

u/shake_wit_dem_fries Feb 16 '15

[ptr whatUpBaby];

Sent you a message ;)

16

u/adi-fractor Feb 16 '15

If anyone wants to "delete tmewett;" just know it's completely safe.

15

u/Schtee Feb 16 '15

You do not have to introduce yourself, for we have met many times.

9

u/brunokim Feb 16 '15

Do you feel threatened by Optional.absent()?

8

u/[deleted] Feb 16 '15

When are you getting your reassignment and how do your parent classes feel about it?

7

u/[deleted] Feb 16 '15

Are you part of an array? Who are your neighbors?

6

u/johnbr Feb 16 '15

true or false?

3

u/ron_krugman Feb 17 '15

FileNotFound

6

u/credditz0rz Feb 16 '15

What do you think about addresses like 0x00000007?

5

u/[deleted] Feb 16 '15

How do you feel about pure virtual calls?

5

u/[deleted] Feb 16 '15

What does it feel like to be given special treatment everywhere you go? People are always looking for you and overwriting you, and some are even calling for your deportation to make room for Maybe and Optional.

6

u/holztxfnel Feb 16 '15

Do you use (page) protection?

3

u/satan-repents Feb 16 '15

submitted 5 hours ago by tmewett from The Butt™

4

u/myhf Feb 17 '15

I see you're running the Butt to Butt extension.

2

u/scshunt Feb 16 '15

Are you a member of the club?

2

u/flarn2006 Feb 17 '15

If I pass *you by reference, but the function only takes the address of the reference without using it directly, will that result in undefined behavior?

2

u/[deleted] Feb 16 '15

printf("%s", (char *)tmewett);

2

u/tubbo Feb 16 '15

y u no lemme itunes

1

u/RenaKunisaki Feb 16 '15

***Segmentation fault.

1

u/cefarix Feb 17 '15

I love you.

1

u/Neebat Feb 17 '15

Can you tell us why we all hate you so thoroughly?

1

u/CrazyM4n Feb 17 '15

Are you ever planning on pointing to anything?

1

u/BarkingToad Feb 17 '15
if(tmewett != null && tmewett.Value != null) {
    Question question = new Question();
    tmewett.Ask(question);
}

I'm sorry, it seems my code does nothing.

1

u/[deleted] Feb 18 '15

You're always blaming this dude Segmentation for your issues. Why are you such a douche? Maybe I really WANT to write to address 0.

1

u/earlgreyfanboy Mar 14 '15

How are you so exceptional?

0

u/Fluffy8x Feb 24 '15

Fuck you!!!!!

0

u/[deleted] Feb 16 '15

[deleted]

155

u/tmewett from The Cloud™ Feb 16 '15

Segmentation fault (core dumped)

36

u/sigma914 Feb 16 '15

There's plenty of valid things you can do with a nullptr. Like compare it with other pointers, cast it to other pointer types... um... ok not plenty of things per se...

16

u/[deleted] Feb 17 '15

You can also yell at them

8

u/Neebat Feb 17 '15

That's kind of automatic, really.

0

u/[deleted] Feb 16 '15

[deleted]

127

u/[deleted] Feb 16 '15

NullPointerException

145

u/DroidLogician Feb 16 '15

Found the managed runtime pleb. We all know real null pointers cause a segfault.

30

u/ron_krugman Feb 16 '15

Segfaults in a managed environment are where it's at.

19

u/RenaKunisaki Feb 16 '15

That takes real skill.

4

u/ron_krugman Feb 16 '15

It's actually pretty easy if you have don't have enough skill to use JNI properly.

3

u/immibis Feb 18 '15

Fun fact: .NET lets access violations happen, and converts them to NullReferenceExceptions when they're caught. It doesn't add null pointer checks for objects below 64k in size.

8

u/[deleted] Feb 16 '15

Guilty as charged... :(

0

u/[deleted] Feb 17 '15

[deleted]

6

u/[deleted] Feb 17 '15

One of the devices I work on DOES throw segfaults (and plenty of them!) but the problem is it won't record data. Which wouldn't be a problem except its whole purpose in life is to record data.

1

u/DroidLogician Feb 17 '15

I'm actually glad the languages I use for fun don't have nullable pointers (except in FFI, ewww). The Optional/Maybe pattern is a godsend.

0

u/[deleted] Feb 17 '15

[deleted]

2

u/DroidLogician Feb 17 '15 edited Feb 17 '15

The big one I'm into right now is Rust, designed by Mozilla as an alternative/companion to traditional C programming that focuses on memory safety and expressibility without the abstraction cost of higher-level managed languages. They actually pride themselves on their growing compatibility with embedded platforms and strong C interop. It's built on LLVM, so it can basically go wherever LLVM goes, provided you can build the libraries you need from the stdlib for the given target. So far it's officially on Windows, Mac OS X, Linux, FreeBSD (unofficially... sorta), Android, and generic ARM devices.

Rust has the Option type which can either be Some(MyType) or None. It's basically a nullable value that the type system requires the user to explicitly handle, but isn't necessarily "blessed" since it just uses Rust's enums (also called "tagged unions"), which means the pattern can be applied to user-defined types as well.

So instead of a function or method call returning MyType that may or may not actually be initialized to a null value that you wouldn't know to check for unless the docs tell you to or you've checked the source, that function would return Option<MyType> and you'd have to explicitly check that the value is available before using it. But I don't think the ergonomics suffer at all:

(I've never written a single line of C so I'm sorry if this is horribly wrong.)

char* get_my_string() {
    // do whatever here
}

void use_non_null_string(char* my_string) {
    // use it here
}

void main() {
    char* my_string = get_my_string();

    if(my_string != NULL) {
        use_non_null_string(my_string);
    } else {
        "String was null!" >> cout;
    }

   // We'll ignore freeing it; maybe it's static
}

Compared to Rust:

fn get_my_string() -> Option<String> {
    // do whatever here
}

fn use_non_null_string(my_string: String) {
    // use it here
}

fn main() {
    let my_string = get_my_string(); // did I mention type inference FTW?

    // Consider this to be a very powerful `switch` block that can pattern-match
    match my_string { 
        // Variable shadowing keeps the namespace small for little semantic cost
        Some(my_string) => use_non_null_string(my_string),
        None => println!("String was null!"),
    }

}

If you forgot the None case, the compiler would complain: Non-exhaustive match block! Rust has strong functional programming influences, which means it lets you do this, too:

// `||` signifies a closure (i.e. lambda); we pass `use_non_null_string` as a first-class function (compiles down to a function pointer!)
get_my_string().map_or_else(use_non_null_string, || println!("String was null!")).;

The Result type builds on this, but replaces None with an Err(MyErrorType), instead, for carrying an error message or incomplete result. It's basically a checked exception that isn't, you know, a horrible disease.

This doesn't even touch the fact that Rust has move semantics and a strong ownership/borrowing system, or that println! is actually a macro that builds a format string at compile time, or the fact that String is a heap-allocated UTF-8 string type that is automatically deallocated when it falls out of scope. Rust is built around RAII and it makes for very elegant code, even when using types that need to release external resources when freed. Don't even get me started on iterators!

It also allows the programmer to skirt the rules using unsafe blocks, which reminds the programmer that there are invariants that need to be dynamically checked when they have to get down and dirty, like calling into linked C functions (which Rust cannot guarantee are safe), or dereferencing raw pointers (distinct from Rust's borrowed references) since they can be null, or avoiding the overhead of multiple bounds-checks when indexing into a vector because once is enough.

Barring compiler or stdlib bugs (which are already very infrequent and becoming even more so) and code in unsafe blocks, which requires due diligence from the programmer, Rust programs are virtually free of most memory errors, including buffer overflows (array/vector indices checked at runtime), use after free (move semantics/ownership), data races (immutable by default, cannot share mutable references across threads), and, of course, null pointers.

And all of this compiles down to assembly that's almost indiscernible in performance from a C program that takes similar measures. Almost all these safety guarantees are only paid-for once, at compile-time.

Okay, I'm a bit of a fanboy, but I think this is all really freaking cool. And I've just barely scratched the surface.

0

u/[deleted] Feb 17 '15

[deleted]

1

u/DroidLogician Feb 18 '15 edited Feb 18 '15

Haskell has the Maybe monad which functions similarly. Via libraries, Java gets the @Nullable annotation that provides linting for null checks, and now the Optional type is in Java 8 to support this pattern wholly. It appears often in languages with strong functional influences because, IMHO, it just works better.

Unsafe blocks aren't a silver bullet. They won't let you turn an immutable reference into a mutable one (at least, not without some trickery); they're just there as a contract between you and the compiler that says you intend to make sure the code you're writing is safe and correct at runtime, because Rust can't do it at compile-time.

Ideally, a pragmatic Rust program should have a very limited number of unsafe blocks. After all, why would you choose Rust for safety if you're going to drive with the airbags off? In fact, it's totally possible to create sizeable programs and libraries without any unsafe blocks at all.

The zinc project I linked early in the previous comment is intended to let you interface with embedded hardware without ever having to venture outside Rust's safety net. I'd bet they'd love some help bootstrapping it on the 186.

1

u/Simmion Feb 24 '15

Java 8 Has optionals.

47

u/MachinaExDeo Feb 16 '15

You're doing it wrong!

void** AddressOfNullPointer = &NullPointer;

23

u/jungle Feb 16 '15

Not really. To cause a NPE you need to ask "what's stored at your address".

6

u/[deleted] Feb 16 '15

He kind of wreaks havoc when you ask him what he's hiding

5

u/katyne Feb 17 '15

don't we all

2

u/[deleted] Feb 16 '15

Shiiiiiiiit... I used to know this stuff when I used C++. Thanks for reminding me ;)

9

u/jungle Feb 16 '15

Actually, if OP is the (null) pointer, "your address" would be the address the pointer is stored at, so the question should be "what's stored at the address that's stored at your address"... if you really care about this, I mean. ;)

And let's not get into a handle...

1

u/shadows1123 Feb 17 '15

I thought a null pointer was simply an address/object pointed at a non-existent object in memory?

2

u/jungle Feb 17 '15

It is. A pointer is a variable holding an address.

Let's say the name of the variable is "op". You can assign a value to it (op = 0), use its value (op == 0), get its address (x = &op), or get the thing it points to (x = *op). Only the last action can raise an exception.

10

u/adi-fractor Feb 16 '15

His address is undefined behaviour

2

u/belikralj Feb 17 '15

And zero...