Crashing when trying to modify constant variable through a pointer [duplicate] - c

This question already has answers here:
Changing value of const int using using pointer [duplicate]
(2 answers)
Closed 8 years ago.
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 ?!

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?

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

Related

Function seems to change where pointer is pointing to [duplicate]

This question already has answers here:
Return address of local variable in C
(5 answers)
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 4 years ago.
I have written following C code:
#include <stdio.h>
#include <stdlib.h>
int *getPointer(int var);
void anotherFunction();
int main ( int argc , char * argv [])
{
int *intPtr = getPointer(3);
printf("%d\n",*intPtr);
anotherFunction();
printf ("%d\n",*intPtr);
getPointer(5);
printf("%d\n", *intPtr);
return EXIT_SUCCESS ;
}
// Which problem occurs here?
int *getPointer(int var) {
int *ptr=&var;
return ptr;
}
void anotherFunction(){
// do nothing
int a [ 5 ] = { 4 , 5 , 6 , 7 , 8 };
}
The Output is:
3
7
5
I do not understand why the value of intPtr changes in the second printf() call. I would appreciate your help!
Thank you
This function is totally pointless and wrong:
int *getPointer(int var) {
int *ptr = &var;
return ptr;
}
ptr points to the local variable var (yes function parameters are more or less the same as local variables). But as soon as the function returns, that variable doesn't exist anymore. So the pointer returned by getPointer points basically to junk.
The pointer you are getting is a pointer to var local variable. And that variable is stored in the STACK (not in heap).
So, a couple of things:
Relying on pointers to STACK variables after the function call ended is just WRONG. Don't do that. Never.
The second printf is printing something in the stack that was overwritten when you called anotherFunction. This worked in this case, but this behavior is UNDEFINED (it could also lead to a SEGMENTATION FAULT).

declared variable of type double gets automatically initialized to inf [duplicate]

This question already has answers here:
what is the default value of char pointer or char variable [duplicate]
(5 answers)
Closed 4 years ago.
I am running my code with gcc. I have a function in which I declare a variable X1 which is initialized to 'inf'.
function(double nu, void *params) {
struct func_params *part= (struct func_params *)params;
double result;
*commands*
if (condition){
double wb,X1;
printf("inside if X1 %e \n",X1);
}
return result;
this code is returning "inside if X1 inf". I never had that issue and I didn't change anything to the code...Any idea what it could be?
It is Undefined bahavior and your unitialized variable can have any value including inf & NaN.
When you use it you invoke the Undefined Behavior

Pass pointer to a literal direct to a function [duplicate]

This question already has answers here:
Pointer to literal value
(12 answers)
Closed 4 years ago.
Given the following piece of C code:
void calc(int *value)
{
// do something with value
}
int main(void)
{
int i;
i = 10;
calc(&i);
}
Is it possible to get rid of setting up i and pass directly 10 to function calc? If yes, how can this be done?
Example of what I have in mind (which doesn't work):
calc( (int *) 10);
Nope, it's impossible to have a pointer to a constant in C.
UPD: however it seems that there is a trick using a struct compound literals syntax (thanks to #antti-haapala for the correction). Try this:
calc(&(int){10});

Why const void* still be updated in C? [duplicate]

This question already has an answer here:
Confusion regarding modification of const variable using pointers
(1 answer)
Closed 6 years ago.
I have some code with const void* as below:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
const int p = 10;
char s[] ="I am newbie";
const void *vp;
vp = &p;
*(int*)vp = 11;
printf("%i\n", *(int*)vp);
vp= s;
printf("%s\n", (char*)vp);
return 0;
}
My question is why const void* vp still be updated?
As my understanding, const variable can not be updated directly, is that correct for all types?
You effectively removed the const when you got a pointer to your int, cast the pointer to something without the const, and then changed the value of what that points to.
*(int*)vp = 11;
You can cast a pointer type to any other pointer type.
Modifying a const variable like this is undefined behavior. For example, the compiler might have seen that the variable was const, realized that it could pre-compute what the printf functions would print, and do the substitution at compile time as an optimization. The compiler would be allowed to do this because it thinks the variable is const.

Use of automatic variable outside its scope in C [duplicate]

This question already has answers here:
What happens when a variable goes out of scope?
(3 answers)
Closed 6 years ago.
I am studying the working of an automatic variable. I know that it is only accessible inside the block or function in which it is declared and its lifetime is within that same function or block. So the following piece of code I am trying to check.
/Declaration of header files/
void testfn(void);
int *p;
int main(void)
{
testfn();
print("%d\n",*p);
return 0;
}
void testfn(void)
{
int x=444;
p=&x;
}
The output is - 444
I am wondering that when the testfn(); exits,the variable x will be destroyed. Then how in main function the pointer (*p) prints 444.
How this works...or if I am missing something.
Please clarify my doubt.
Thanks
It is coincidence that the original value still remains. With another compiler, or with another compilation configuration, it could take any other value or the program could just crash.
If between the testfn and printf functions you call any other function that does something with its local variables, you might see that the 444 value is not obtained anymore. But this is just, again, coincidence.
p points to the stack where x was stored. If the memory location hasn't been used for something else you will most likely get 444.
Try to insert another function call before printing p and see what happens:
#include <stdio.h>
#include <math.h>
void foo() {
int y=123;
}
void testfn(void);
int *p;
int main(void)
{
testfn();
foo();
printf("%d\n",*p);
return 0;
}
void testfn(void)
{
int x=444;
p=&x;
}
On my machine, the output is now:
123
Since the code results in undefined behaviour, the result could be different if I try this on another platform. But you can see that undefined behaviour can lead to strange bugs.
The memory location that was previously reserved for variable x is not overwritten yet. But it may be at any time. That's why your code leads to undefined behaviour.
In the following example, the memory location that was previously reserved for variable x will be overwritten by the value that is assigned to the variable y. Since the pointer p still points to that location, *p will evaluate to this new value:
#include <stdio.h>
int *p;
void test1(void) {
int x = 444;
p = &x;
}
void test2() {
int y = 15;
}
int main(void) {
test1();
test2();
printf("%d\n",*p);
return 0;
}
The fact that the value still remains is completly coincidental (not guaranteed) because nothing has overwritten it yet.
You can not count on this, it may fail, may print garbage or may crash your program or pc even.
Don't use this, it is considered undefined behavior.

Resources