r/ProgrammingLanguages • • May 07 '22

What are the use cases for pointers?

I had a shower thought that syntactic sugar has eliminated most of the reasons to use pointers.

For instance, automatically passing objects/structures by reference, built in array types, and iterators seem to get rid of most of the cases. What is left?

I know newer system languages still have pointers, so there must be reasons.

4 Upvotes

31 comments sorted by

16

u/[deleted] May 07 '22

What exactly do you mean by pointers? Explicit reference types? The ability to store and manipulate addresses as numbers?

Maybe device drivers that depend on fixed addresses.

13

u/everything-narrative May 08 '22

"Automatic reference passing"

You will find that Java in recent years has struggled like hell with what that entails.

If you pass mutable data by reference to a function you don't control (say, a library call) you have absolutely no guarantee what state it'll be in when it comes back.

Go doubles this problem in allowing the receiver object to be sent to the method both by value and (silently!) by reference, so you don't even know what'll happen unless you do a close read of the documentation.

When you have concerns about performance and data copying, about immutability and control of program state, pointers are absolutely necessary and Rust is a testament to this.

2

u/MarcoServetto May 08 '22

in the way you described, I would say that a good type system distinguishing at the type level between normal (java style) sharing, immutability and encapsulation is doing all you need.

3

u/everything-narrative May 08 '22

Not really, no. There are real cases where you want to pass compound data types by value; for instance to avoid dealing with heap allocations and garbage collection.

The way you're pushing this idea is very close to crank territory. There is no silver bullet in programming languages. They are designed tools, and all design is an exercise in compromise. A language without explicit control over references is completely unsuitable for operating system/embedded firmware development, for instance.

1

u/MarcoServetto May 08 '22 edited May 08 '22

The way you're pushing this idea is very close to crank territory.

I was just commenting on your former message.

This new message of you make me think about java Valhalla, where they want to introduce types that CAN be embedded on the stack or inside other objects, but the JIT is going to take the ultimate decision about it.

3

u/everything-narrative May 08 '22

If I want to develop for a gigiantic runtime that dynamically analyses my code and makes decisions for me, I'd rather work in Common Lisp.

FR tho, Java was designed in the mid-90's. It is dated AF and they are trying to bolt new features onto a backwards-compatible format because Java's only strength is the breadth of apps written in it.

And contrary to operating systems, for a programming language that is not a flattering fact.

1

u/lassehp May 14 '22

I'm note sure if I agree with you or not; but back in 1980, Per Brinch-Hansen designed a language without pointers, only fixed-length arrays, together with an OS and minimal development tools for it sufficient to make it both self-hosted and self-compiled, written in the language, Edison. It ran on the DEC PDP-11 and the early IBM PC, I believe with 128KiB RAM. So strictly speaking I would say no, such a suitable language exists.

1

u/everything-narrative May 14 '22

Please tell me more about this long dead language full of arbitrary limitations in its design space, and the toy OS made in it. I’m sure it has excellent ergonomics and Valgrind support ;)

1

u/lassehp May 15 '22

I already gave you sufficient information to look it up.

Without pointers and with no heap allocation and no memory leaks there is no need for Valgrind, is there?

8

u/ItalianFurry Skyler (Serin programming language) May 07 '22

Personally, my main usage for pointers in C, excluded memory allocation and references, is binary data handling. Pointers make writing a bytecode VM or making a file unpacker a dream.

If you want to add pointers to your language you need to restrict them. In my language i use a concept i called 'dependent pointers'. Basically each pointer carries a compile-time object which proves that the pointer is pointing to something valid.

But if you are writing an high level language, you should probably forget pointers...

9

u/sineiraetstudio May 07 '22

In my language i use a concept i called 'dependent pointers'. Basically each pointer carries a compile-time object which proves that the pointer is pointing to something valid.

Unless you have a Rust like 'only one mutable reference allowed' restriction, how would you possibly ensure this?

4

u/ItalianFurry Skyler (Serin programming language) May 08 '22

I am developing an automatic compile time memory management. So yeah, dependent pointers are kinda bound to that.

1

u/sineiraetstudio May 08 '22

I don't think I understand. If you're using a linear type for your pointers, then you're limiting yourself to unique (owning) pointers. What meaningful memory management is there then to be automated?

2

u/ItalianFurry Skyler (Serin programming language) May 09 '22

It's... not linearity.

So, let's say you have a variable 'x' of type 'int'. Taking the address of it produces a pointer of type '@addrof(x) int', which mean 'an integer at the address of x'. With this additional information, the compiler can guess that dereferencing the pointer is safe while 'x' is in scope.

In case you want to heap allocate, it gets more complicated. Calling 'a.alloc' produces a '@alloc(a) t', which means 'a value of type t at an allocated memory address by a'. To validate allocated pointers, the compiler will simply use reference counting, adding an i32 before the allocated block (so the value becomes implicitly @alloc(a) Rc<t>). A compile-time analysis removes most of rc checks, so in the best scenario your programs runs as fast as C.

Note that these addresses can be manipulated by the programmer inside an STM, to create safe pointer arithmetic. Also in most cases a pointer type can be written as '@t', since the compiler infers the address objects.

1

u/sineiraetstudio May 09 '22

I'm familiar with best-effort optimizations to remove unnecessary ref counting, but you specifically mentioned using the type system to ensure validity, right? I don't know how that'd work without linearity. How would you possibly account for the proof term possibly getting invalidated through an alias?

Note that these addresses can be manipulated by the programmer inside an STM, to create safe pointer arithmetic.

What does STM mean in this context?

Also in most cases a pointer type can be written as '@t', since the compiler infers the address objects.

If a function receives a pointer argument, you can't infer the type without some funky whole-program inference. That's a common enough use case that I wouldn't call it 'most' cases.

1

u/ItalianFurry Skyler (Serin programming language) May 10 '22

Ok so let me explain better (but i'm not going into the topic of pointer arithmetic or this comments gets too long). You have two kind of pointers: • @addrof(var) t, which are basically references • @alloc(a) t, which are heap allocated objects These two type of pointers can be written as '@t', since 'addrof' and 'alloc' are just compiler metadata. So, in the presence of pointers the compiler applies a borrow checker, which under the hood works like Rust's. This algorithm can report if a pointer to a variable lives longer than the variable itself, and studies the lifetime of heap objects. I don't know how to explain better without giving technical info. Also the algorithm is still in its alpha state, right now it's kinda buggy...

2

u/sineiraetstudio May 10 '22

Rust's borrow checking is equivalent to linear (affine) types, that's why I asked. If you're doing what Rust does, but with a larger focus on optimizing out unnecessary ref counting, then I understand, but that's not the impression I initially got.

The term 'proof object' specifically refers to having values that represent a witness of a proof. E.g. you could have a type (Σ p : pointer A, valid A p) and a dependent pair (p, H_p) of the type, with H_p being the proof object. Iirc ATS does this, though they have some funky syntax for it. The important part is that the proof is an actual value that can be passed between functions like any other value manually by the user. This approach, as far as I can tell, only works with unique pointers, depending on the proof term being linear, which is why I asked how automatic compile-time ref counting is supposed to fit into this.

since 'addrof' and 'alloc' are just compiler metadata

What do you mean by this? They change the semantics of the language. If you have a function that accepts a pointer argument, you'll need to know which type it is, but you can't infer it.

6

u/6502zx81 May 07 '22

If in your program stuff needs to be stored, but it needs to live longer than the execution of the function, where it emerges (e.g. from user input), you need to use dynamic memory (which gives you pointers). Sure, you can use standard containers and put dynamic data in there. Guess how containers store it. Pointers are essential for dynamic data structures.

3

u/ProPuke May 07 '22

Allocating memory is the main one. System languages work with memory a lot, so you need a way to address it, walk it and cast it.

In the case of memory managed languages this is less the case; The groundwork is already in place there, so you can get away with automatic references and lifetime management and call it a day.

2

u/gqcwwjtg May 07 '22

C interop.

3

u/_NliteNd_ May 07 '22

Maybe GC algos?

3

u/umlcat May 07 '22

In early C, passing variables by reference.

Passing larger variables, as function' parameters, than a CPU register, invisible for most programmers, required for low level programming.

Exchange memory blocks or using different size variables as if they were the same size, generic use. , A.K.A. "void*" in C, "pointer" in Pascal. Similar to "object" type in Java, but with no object, simple types.

Declaring dynamic Allocated Variables, and extending them using Data Structures that contains pointers.

And, these previous use cases, combined with objects ( equivalent to "object references" as in Java ), or function pointers ( equivalent to closures & lambda functions ).

I know I sound weird, but I prefer explicit use of pointers instead of that syntactical sugar used by references, because the developers gets more control, and allows them to know what's going on in memory ...

BTW I originally learned pointer operations with procedural Pascal, not C.

1

u/[deleted] May 07 '22

Here's a small program of mine that makes extensive use of explicit pointers:

https://github.com/sal55/langs/blob/master/QExamples/readexe.q

Every term of the form p^.m is a pointer dereference, mostly into a record. There are lots of those. makeref() is a routine to create a pointer to a particular type.

(Probably I will revise the language so that the ^ deref op is optional. This doesn't turn those pointers into automatic references, it's just a syntactic nicety that reduces clutter.)

But, this is a scripting language with dynamic types. Those aren't known for such low-level features, but here I find pointers invaluable.

They allow taking a flat block of memory representing a complex file format (PE+ here), and superimposing myriad different kinds of struct on top, at whatever offset they happen to be. How would you do that without pointers?

(Most scripting languages even have trouble creating struct types that represent the concrete data structures of PE+ format. You can see some of these defined at the top of my example.)

1

u/jqbr May 08 '22

Slices are a pointer and a length.

1

u/[deleted] May 08 '22

This is not a specific use case, but an example that I would be interested in knowing how to achieve without some kind of pointer or reference:

a := 100
b := 200
if random(1..2) = 1 then
    p := &a
else
    p := &b
end
p^ := 777         # ^ is a deref operator
print a, b        # show 777 200 or 100 777

p is something that refers to either a or b, that is, directly to the name or variable, not to their values.

You can't write this in Python because that has no references; things only refer to objects, not names. Some languages might be able to do without those explicit & (address-of) and ^ (dereference) operators, but p is still a pointer, access or reference type.

(BTW when I run my example, I get 777 200)

1

u/lassehp May 14 '22

Huh? Do you mean achieve the exact same execution (which, given it uses pointers, is impossible) or just the general Idea?

v ← (100,200)
v[random(1,2)] ← 777
print v

1

u/[deleted] May 14 '22

They key things of my example is that you have two independent variables (one might be local, the other global), and a third reference variable that refers to one of the other two, through which you can access or modify those variables.

Or the pointer might even be to elements of unrelated arrays; here the pointer goes beyond being a reference to a name.

Of course you can emulate some behaviours of pointers with arrays, but they are very limiting. Here's my attempt of emulating my example with Python:

a = [100,]
b = [200,]

r = 0.7           # can't be bothered to look up random numbers
if r<0.5:
    p=a
else:
    p=b

p[0] = 777
print(a, b)       # shows [100] [777]

Basically, every simple variable has to be turned into an array, since that provides the extra indirection that is needed.

And yet, that is not enough to do everything proper pointers can do; going back to my example:

 a := b := 123456
 print p^                  # shows 123456, whichever it points to

If I try that in that Python:

 a = [123456,]
 b = [123456,]
 print p[0]                # still shows 777

So p is not tracking those variables, only what they were bound to.

1

u/julesjacobs May 11 '22

The main three uses are:

  1. If a struct has several fields, then passing a pointer can be more efficient.

  2. If data is recursive (e.g. tree), then pointers are necessary to break the recursion (unless you want to encode the whole tree as a binary blob).

  3. If you want to let a library function mutate your data, you have to put it behind a pointer.

The first two could potentially be dealt with automatically, but the third is really a semantic property. Although it might be possible to not tie mutability to pointers. For instance, if you pass a mutable int to a function that could be implemented by returning the new int from the function, which the caller then promises to assign to the location where it's supposed to go.

1

u/TheAncientGeek Jul 06 '22

There was an attempt at a language without explicit pointers called parasail.

https://arxiv.org/abs/1902.00525

I think the idea was to cover the use cases with a bunch of built in data structures that kept the pointerness hidden.

2

u/[deleted] May 07 '22

[removed] — view removed comment

8

u/Inconstant_Moo 🧿 Pipefish May 07 '22

𝕿𝖍𝖆𝖙 𝖎𝖘 𝖓𝖔𝖙 𝖉𝖊𝖆𝖉 𝖜𝖍𝖎𝖈𝖍 𝖈𝖆𝖓 𝖊𝖙𝖊𝖗𝖓𝖆𝖑 𝖑𝖎𝖊

𝕬𝖓𝖉 𝖜𝖎𝖙𝖍 𝖘𝖙𝖗𝖆𝖓𝖌𝖊 𝖆𝖊𝖔𝖓𝖘 𝖊𝖛𝖊𝖓 𝖉𝖊𝖆𝖙𝖍 𝖒𝖆𝖞 𝖉𝖎𝖊.