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).
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a function as follows:
void foo (int *check){
*check= 9;
printf("*check: %d\n",*check);
//when I print "*check" here, the value changes as 9.
}
This is the main function.
void main () {
int check=5;
foo(&check);
printf("check: %d\n",check);
//when I print "check", gives me 5.
}
I want to change the value of "check" variable but it does not work. Where am I making mistake? Thank you!
I am using makefile while running it.
Edit: malloc is deleted now it gives me Segmentation fault (core dumped) error
When you malloc within foo, the dereference now points to the value malloced within the function's scope. This means that the value within the function is changed and not the value outside of the function. To correct this, you don't need to malloc within the function to change the value of check:
void foo (int *check) {
*check= 9;
}
void main () {
int check = 5;
foo(&check); // check is now 9
}
You are doing everything just fine, the only thing that is wrong is trying to malloc the variable you passed to the function , since it is already allocated on stack. In order to do what you're trying to do, you should declare the integer as pointer to integer (int *check) outside the function, and avoid using the & character when calling the function with the pointer as parameter.
To change a variable through a function you need to pass it by reference, not value. Your title and code do not match.
Here is a version with both kinds of arguments, side by side:
#include <stdio.h>
int foo(int *ref, int val) {
*ref = 1122; // by reference
val = 1155; // by value
printf("inside:\n%d %d\n", *ref, val);
return val; // otherwise "val=1155" is lost
}
int main(void) {
int ree = 12; // "referencee"
int v = 15;
printf("main:\n%d\n", foo(&ree, v)); // return value (1155)
printf("%d %d\n", ree, v); // 1122 and 15
}
ree is passed as &ree to ref; this address/pointer gets dereferenced inside the function with *ref to change ree's value.
You passed the variable check to the function foo by reference through a pointer to it
int check=5;
foo(&check);
So dereferencing the pointer you could get a direct access to the variable check and could change it like
*check= 9;
However within the function you reassigned the pointer with a new address of a dynamically allocated memory
check= malloc(sizeof(int));
So now the pointer check doe not point to the original object passed to the function by reference. As a result this statement
*check= 9;
changes the dynamically allocated object of the type int instead of changing the variable passed to the function by reference.
Edit: malloc is deleted now it gives me Segmentation fault (core
dumped) error
It is a bad idea to change such dramatically the code in the question because it will only confuse readers of the question and answers. Neither segmentation fault should occur. It seems the new provided code in the question does not correspond to the actual code that generates a segmentation fault.
Here is a demonstrative program. It compiles and runs successfully.
#include <stdio.h>
void foo ( int *check )
{
*check = 9;
printf( "Inside foo check = %d\n", *check );
}
int main(void)
{
int check = 5;
printf( "Before foo check = %d\n", check );
foo( &check );
printf( "After foo check = %d\n", check );
return 0;
}
The program output is
Before foo check = 5
Inside foo check = 9
After foo check = 9
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.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
I managed to condense the code where the problem occurs to this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct
{
double height;
double hello;
}Variables;
void information(Variables **Constants);
int main()
{
Variables *Constants=NULL;
information(&Constants); //Assigns values to the structure pointer
printf("Height %lf \n",Constants->height); //These print correctly only
printf("hello %lf \n",Constants->hello); //intermittently
return(0);
}
void information(Variables **Constants) //Assigns values structure pointer
{
Variables *consts,constants;
constants.height=10;
constants.hello=20;
consts=&constants;
*Constants=consts;
printf("Height %lf \n",constants.height); //These always print correctly
printf("hello %lf \n",constants.hello);
return;
}
From what i understand, this code should create a structure pointer in main, *Constants. This pointer is then passed into the function using information(&Constants). In information() another pointer is created and assigned a structure variable. The variable is then filled and the pointer is assigned to *Constants, allowing the entire struct to then be passed back to main().
If i print the structure inside information(), the values are correct. However if i print the values in main() the values are sometimes correct, or they print random numbers. Any help in understanding this would be appreciated.
You are returning a local variable from function. this is causing problem.
when the program exists from function information() the variable constants whose address you use in main is already out of scope.
To solve this problem you need to create the object in function information() using dynamic allocation. and deallocate this memory dynamically allocated in main.
This question already has answers here:
Using Double Pointers after memory allocated within function
(3 answers)
Closed 7 years ago.
#include <stdio.h>
#include <stdlib.h>
char** mlc(char** f){
int count=10;
int size=10;
f=(char**)malloc(count*sizeof(char*));
for(int i=0;i<count;i++){
f[i]=(char*)malloc(size*sizeof(char));
}
return f;
}
int main()
{
char** f;
f=mlc(f);
f[0][0]='1';
f[0][1]='\0';
printf("%s",f[0]);
return 0;
}
I use this code can work perfectly ,But when I use the following code ,It will get segmentation fault:
#include <stdio.h>
#include <stdlib.h>
void mlc(char** f){
int count=10;
int size=10;
f=(char**)malloc(count*sizeof(char*));
for(int i=0;i<count;i++){
f[i]=(char*)malloc(size*sizeof(char));
}
return f;
}
int main()
{
char** f;
mlc(f);
f[0][0]='1';
f[0][1]='\0';
printf("%s",f[0]);
return 0;
}
So ,the main difference is the first code I return the pointer, why the second code get fault?
In C, function arguments are passed by value. So, from inside the function, you cannot change the value of a parameter and expect the change to be reflected onto the variable passed in by the caller.
In simple words, in your case, from inside mlc(), you can change the value of *f, and that will be reflected onto the *f in main(), but you cannot change the value of f itself.
You first case works, because after allocating memory and pointing the parameter f at it, you return said pointer and retrieve it into f in main(). So, in main(), f is perfectly valid for usage.
Your second case fails, because after returning from the function, f in main() remains uninitialised.
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.