'Branch Instruction Inline ARM Assembly Causes Seg Fault [duplicate]

I wrote the following code based of off Confusion about different clobber description for arm inline assembly and it works fine:

#include <stdio.h>

int variableToBeWritten;
int value = 5;

void criticalSection(){
    printf("in critical section\n");
    fprintf(stderr, "important value is %d", variableToBeWritten);
}

int main()
{
    asm volatile(
        ""
        :  "=r" (variableToBeWritten)
        :  "0" (value)
        );
   criticalSection();
  return 0;
}

The output is as expected when compiled with gcc gcc main.c -g -lpthread -O0

in critical section
important value is 5

However, I'd like to make the criticalSection() function call within the inline ASM code, so I used a BL instruction.

I replace the criticalSection() C function call with the line "BL criticalSection". Here is the modification to the main() function:

    asm volatile(
        "BL criticalSection"
        :  "=r" (variableToBeWritten)
        :  "0" (value)
        );

and here is the output

in critical section
important value is 0Segmentation fault

So not only does the value not get properly written, a segmentation fault occurs.

Any help concerning this behavior, and how to properly use the BL instruction here, would be much appreciated.

My version of gcc is g++ (Raspbian 8.3.0-6+rpi1) 8.3.0.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source