4 ms·
setjmp and longjmp are very low-level and kind of borderline use-case. I practically almost never use those.
by stephc_int13 4y ago
setjmp and longjmp are very low-level and kind of borderline use-case.
I practically almost never use those.
- gavinhoward 4y agoAnd that makes sense. For me, I have a stack allocator that knows about cleaning up, as well as about setjmp and longjmp, so I have a function I can call that will deallocate everything in the stack allocator and do the jump. It's basically a safe exception because everything will be cleaned up properly (if I allocate everything on the stack allocator or be rooted in the stack allocator, which I do).
- marssaxman 4y agoIs this allocator by any chance available online somewhere? I'd like to read and possibly use it.
- gavinhoward 4y agoIt's currently under three licenses to make it as radioactive as possible while the software it supports is under development. Once I'm done, however, it's going to be under a single copyleft license because I never meant it to be incorporated into any code other than my monorepo. It also doesn't even use malloc(), so you wouldn't care about a lot of the details. Links to it are in my comments, but I wouldn't look at it. Instead, I'll describe something you can implement with helps that would be much simpler. Keep a stack of data about allocations. You should keep a pointer to the allocation, the size, and the "destructor" (a function pointer to a function that takes a void pointer and returns nothing). Write 3 destructors. Two should do nothing, but they should be separate. One should be for scopes, and the other should be for functions. The last destructor should cast its void pointer to a jmp_buf pointer and do a longjmp() on it. Then have a normal allocation and deallocation function on the allocator. This is for normal allocations. Have a function to enter a scope, enter a function, and set a jump. In each case, they should push data onto the stack with the appropriate destructor. (I push a pointer to the function name for functions, for debugging.) Then have functions to exit a scope, exit a function, and do a jump. These should "unwind" all allocations until they reach an allocation that uses the scope destructor, function destructor, and setjmp() destructor, respectively. (You can text if two function pointers are equal to each other.) I'll be happy to answer any more questions.
- marssaxman 4y agoThank you for the description.