Segmentation fault with setjmp() and a jmp_buf array

Started by Thomas Mertes, May 30, 2026, 07:46:21 AM

Previous topic - Next topic

Thomas Mertes

If I compile and run the program below with gcc it writes:

In main
malloc successful
okay

Other C compilers have also no problem with this test program.
If I compile and run this test program with Pelles C it
triggers a segmentation fault after writing:

In main
malloc successful

This is the test program:

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

#define do_setjmp(jump_buf) setjmp(jump_buf)
typedef jmp_buf catch_type;
catch_type *catch_stack;
size_t catch_stack_pos;
size_t max_catch_stack;

int main (int argc, char **argv)
{
  int fail_value;
  catch_stack_pos = 0;
  max_catch_stack = 128;
  printf("In main\n");
  fflush(stdout);
  catch_stack = (catch_type *)(malloc(max_catch_stack * sizeof(catch_type)));
  if (catch_stack != NULL) {
    printf("malloc successful\n");
    fflush(stdout);
    if ((fail_value = do_setjmp(catch_stack[catch_stack_pos])) == 0) {
      printf("okay\n");
      fflush(stdout);
    }
  }
  return 0;
}

TimoVJL

#1
An alignment error at memory for jmp_buf at x64

Simple test:
catch_type *pcs;
...
  catch_stack = (catch_type *)(malloc(max_catch_stack * sizeof(catch_type)+8));
  pcs = (catch_type *)(((long long)catch_stack) + ((long long)catch_stack % 16));
  printf("%p %p\n", catch_stack, pcs);
...
if ((fail_value = do_setjmp(pcs[catch_stack_pos])) == 0) {

Dynamic jmp_buf should allocated using aligned_alloc() function for x64.

Quote7.24.3 Memory management functions
1 The order and contiguity of storage allocated by successive calls to the aligned_alloc, calloc,
malloc, and realloc functions is unspecified. The pointer returned if the allocation succeeds is
suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental
alignment requirement and size less than or equal to the size requested. It may then be used to
access such an object or an array of such objects in the space allocated (until the space is explicitly
deallocated).
May the source be with you

MrBcx

Another observation:

If compiled to 32-bit:

In main
malloc successful
okay


If compiled to 64-bit:

In main
malloc successful
unhandled exception
Bcx Basic to C/C++ Translator
https://www.bcxbasiccoders.com