Segmentation fault with setjmp() and a jmp_buf array

Started by Thomas Mertes, Today at 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

An alignment error at memory for jmp_buf

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) {
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