ShellCode not running as expected - showing segmentation fault core dump

Hi there,
I have already run this command. But my shellcode is not working for me:

#include <stdio.h>

unsigned char code[] = "\xb8\x0a\x00\x00\x00\xc3";

int main(int argc, char **argv) {
  int foo_value = 0;

  int (*foo)() = (int(*)())code;
  foo_value = foo();

  printf("%d\n", foo_value);
}

gcc -fno-stack-protector -z execstack test.c -o test
./test
Segmentation fault (core dumped)

uname -a
Linux AAAA 5.13.0-30-generic #33~20.04.1-Ubuntu SMP Mon Feb 7 14:25:10 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

I have already identify the following command:
gcc -c -O3 ex.c
objdump ex.o -d

ex.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <foo>:
   0:	f3 0f 1e fa          	endbr64 
   4:	b8 0a 00 00 00       	mov    $0xa,%eax
   9:	c3                   	retq   

You don’t store the array code on the stack. The global static data is not executable. Only the “normal code” and the stack (because -z execstack) is executable.

Move the array code into a local variable in the function. Then the array code will be stored on the stack.

#include <stdio.h>

int main(int argc, char **argv) {
  int foo_value = 0;
  unsigned char code[] = "\xb8\x0a\x00\x00\x00\xc3";

  int (*foo)() = (int(*)())code;
  foo_value = foo();

  printf("%d\n", foo_value);
}