-1

I got a program crash when I am trying to modify constant variable through a pointer.

#include <stdio.h>

static const int x = 5;

void changeX(int *x)
{
    (*x) = 20;
    printf("%d", (*x));
}

int main(void)
{
    printf("Jelele");
    changeX((int *)&x);
    return 0;
}

I know it isn't a good practice and there is no need to make such that ... I am just testing something ...

My question is:

Why program crashes ?!

Armia Wagdy
  • 567
  • 6
  • 22

2 Answers2

2
static const int x = 5;

This is a constant variable stored in read-only location so when you try to write to this location then you see a crash.

Like

(*x) = 20; /* This is UB */

Check the below link:

Where are constant variables stored in C?

Community
  • 1
  • 1
Gopi
  • 19,784
  • 4
  • 24
  • 36
1

You could change where the pointer x points to, but as the integer x is constant, its value cannot obviously be changed by definition.

Roope Hakulinen
  • 7,326
  • 4
  • 43
  • 66