Pointer is giving unexpected value - c

void first(){
int x;
int *p;
p= &x;
scanf("%d",p);
printf("The value in x or *p is: %d\n",x);
}
void second(){
int x;
int *ptr;
scanf("%d",&x);
printf("The value in *ptr is: %d\n",*ptr);
}
int main(){
first();
second();
}
In the above code the second() function is miss behaving.What ever value I give for the x variable that value is getting assigned to *ptr as well as to x. Why?

You didn't assign p a value, so it remains uninitialized. Attempting to dereference that pointer invokes undefined behavior.
Give p a value and you'll get the result you expect:
int *p = &x;
The fact that your code is still printing the correct value is part of that undefined behavior. One of the ways undefined behavior can manifest is that the code appears to work properly, but then a seemingly unrelated change will cause it to break.
In this particular situation, the functions first and second each define 2 local variables of the same type and in the same order. After the call to first completes, the memory that contained the values of x and p from that function still contain those values, but there have been no other function calls yet to overwrite them.
When you then call second immediately after first. The variables x and ptr in second end up using the same memory as x and p in first. And because ptr is uninitialized, it still contains the old value which is the address of x in first, which happens to be the same as the address of x in second.
Again, this is undefined behavior, so you can't depend on this happening all the time. If you added another variable to first or called another function between first and second, that will modify the stack memory previously used by first. Then than memory would contain some other value and you'll probably either print a garbage value or core dump.
The same code may give different results if compiled with a different compiler or different compiler options. For example, another compiler may choose to put the variables in each function in a different order on the stack, or it could decide to zero out the stack used by a function after the function returns.

int *p=&x;
The address of x gets stored in p.
printf("%d",*p);
Since p has the address of x, *p basically means that you are going to the location specified by p and picking up the item, which is the value of x.

Related

Double Pointer and Local Scope Confusion

I am taking a c programming course on Udemy and am quite confused when passing a double pointer into a function. In the example, the instructor passes the address of a pointer as an argument to a function. Then, he de-references that double pointer parameter in the function and sets it equal to the address of a local variable (a).
#include <stdio.h>
#include <malloc.h>
void foo(int **temp_ptr)
{
int a = 5;
*temp_ptr = &a;
}
int main()
{
int *ptr = NULL;
ptr = (int*) malloc(sizeof(int));
*ptr = 10;
foo(&ptr);
printf("%d\n", *ptr);
return 0;
}
So, what we are doing here is changing the value of ptr to hold the address of a. Then, when we de-reference ptr, it should display the value of 5 and not 10, since we changed the value of ptr to hold the address of a.
This is indeed correct: it displays 5 and not 10.
However, what doesn't make sense here is that the variable a is in the local scope of the foo function. When we declare a, the memory allocated is put onto the stack frame; thus, when leaving the local scope of the function that memory is deleted and the frame is popped off of the stack. How can we still access that variable a with the ptr variable in the main function? Shouldn't that memory be completely wiped out?
Then, when we de-reference ptr, it should display the value of 5
Should is incorrect. printf("%d\n", *ptr); is undefined behavior (UB) as the address stored in ptr is invalid with the return of foo(&ptr);.
Output may print 5, may print 42, may crash. It is UB.
... correct that the memory of the stack should be completely wiped out
No. There is not specified wiping of memory. The result is UB.
But sometimes undefined behavior works?
"undefined behavior" is undefined. Even if it "works" today, it may not "work" tomorrow.
When we declare a, the memory allocated is put onto the stack frame; thus, when leaving the local scope of the function that memory is deleted and the frame is popped off of the stack.
This assumes an underling code model that is not specified by C. Other real possibilities exist.
How can we still access that variable a with the ptr variable in the main function?
As is, no defined way. Alternatively keep the address of a valid by making a static.
In Foo function, we are updating the address of our pointer. int a declared in foo function will be stored at some memory location. Now, we are assigning that location to our ptr(which is okay, ptr can point to any memory location of type int). But the issue is the value at that location is not in our control and this location can be used for any other purpose which may update the value at that location.
It means that our pointer is now pointing to location that may be updated by any other source.

What is the difference between derefencing and assigning the address of a variable to pointer variable in C?

See the two codes below!
int main() {
int a = 12;
int *p;
*p = a;
}
and the this code,
int main() {
int a = 12;
int *p;
p = &a;
}
In the first piece of code dereferenced the pointer as this *p = a, and in the second piece of code, the address of variabe a is set to the pointer variable.
My question is what is the difference between both pieces of codes?
In your first piece of code:
int main() {
int a = 12;
int *p;
*p = a;
}
you have a serious case of undefined behaviour because, what you are trying to do is assign the value of a to the int variable that p currently points to. However, p has not been assigned an 'address', so it will have an arbitrary - and invalid - value! Some compilers may initialise p to zero (or NULL) but that is still an invalid address (on most systems).
Your second code snippet is 'sound' but, as it stands, doesn't actually achieve anything:
int main() {
int a = 12;
int *p;
p = &a;
}
Here, you are assigning a value (i.e. an address) to your pointer variable, p; in this case, p now points to the a variable (that is, it's value is the address of a).
So, if you appended code like this (to the end of your second snippet):
*p = 42;
and then printed out the value of a, you would see that its value has been changed from the initially-given 12 to 42.
Feel free to ask for further clarification and/or explanation.
Declaring *p and a is reserving some space in memory, for a pointer in first case, for what a is in the 2nd case (an int).
In these both cases, their values are not initialized if you don't put anything in it. That doesn't mean there is nothing in it, as that is not possible. It means their values are undetermined, kind of "random" ; the loader just put the code/data in memory when requested, and the space occupied by p, and the one occupied by a, are both whatever the memory had at the time of loading (could be also at time of compilation, but anyway, undetermined).
So you take a big risk in doing *p = a in the 1st case, since you ask the processeur to take the bytes "inside" a and store them wherever p points at. Could be within the bounds of your data segments, in the stack, somewhere it won't cause an immediate problem/crash, but the chances are, it's very likely that won't be ok!
This is why this issue is said to cause "Undefined Behavior" (UB).
When you initialized a pointer you can use *p to access at the value of pointer of the pointed variable and not the address of the pointed variable but it's not possible to affect value like that (with *p=a). Because you try to affect a value without adress of variable.
The second code is right use p = &a
The first one is bad:
int main() {
int a = 12;
int *p;
*p = a;
}
It means: put the value of variable a into location, pointed by pointer p. But what the p points? probably nothing (NULL) or any random address. In best case, it can make execution error like access violation or segmentation fault. In worst case, it can overwrite any existing value of totally unknown variable, resulting in problems, which are very hard to investigate.
The second one is OK.
int main() {
int a = 12;
int *p;
p = &a;
}
It means: get the pointer to (existing) variable a and assign it to pointer p. So, this will work OK.
What is the difference between dereferencing and assigning the address of a variable to pointer variable in C?
The latter is the premise for the first. They are separate steps to achieve the benefit of pointer dereferencing.
For the the explanation for where the difference between those are, we have to look what these guys are separately:
What is dereferencing the pointer?
First we need to look what a reference is. A reference is f.e. an identifier for an object. We could say "Variable a stands for the value of 12." - thus, a is a reference to the value of 12.
The identifier of an object is a reference for the value stored within.
The same goes for pointers. pointers are just like usual objects, they store a value inside, thus they refer to the stored values in them.
"Dereferencing" is when we "disable" this connection to the usual value within and use the identifier of p to access/refer to a different value than the value stored in p.
"Dereferencing a pointer" means simply, you use the pointer to access the value stored in another object, f.e. 12 in a instead through its own identifier of a.
To dereference the pointer the * dereference operator needs to precede the pointer variable, like *p.
What is assigning the address of a variable to a pointer?
We are achieving the things stated in "What is dereferencing a pointer?", by giving the pointer an address of another object as its value, in analogy like we assign a value to a usual variable.
But as opposed to usual object initializations/assignments, for this we need to use the & ampersand operator, preceding the variable, whose value the pointer shall point to and the * dereference operator, preceding the pointer, has to be omitted, like:
p = &a;
Therafter, The pointer "points" to the address the desired value is stored at.
Steps to dereferencing a pointer properly:
First thing to do is to declare a pointer, like:
int *p;
In this case, we declare a pointer variable of p which points to an object of type int.
Second step is to initialize the pointer with an address value of an object of type int:
int a = 12;
p = &a; //Here we assign the address of `a` to p, not the value of 12.
Note: If you want the address value of an object, like a usual variable, you need to use the unary operator of &, preceding the object.
If you have done these steps, you are finally be able to access the value of the object the pointer points to, by using the *operator, preceding the pointer object:
*p = a;
My question is what is the difference between both pieces of codes?
The difference is simply as that, that the first piece of code:
int main() {
int a = 12;
int *p;
*p = a;
}
is invalid for addressing an object by dereferencing a pointer. You cannot assign a value to the pointer´s dereference, if there isn´t made one reference before to which the pointer do refer to.
Thus, your assumption of:
In the first piece of code I dereferenced the pointer as this *p = a...
is incorrect.
You do not be able to dereference the pointer at all in the proper way with *p = a in this case, because the pointer p doesn´t has any reference, to which you are be able to dereference the pointer correctly to.
In fact, you are assigning the value of a with the statement of *p = a somewhere into the Nirwana of your memory.
Normally, the compiler shall never pass this through without an error.
If he does and you later want to use the value, which you think you´d assigned properly by using the pointer, like printf("%d",*p) you should get a Segmentation fault (core dumped).

How do I use pointers? in C

Im fairly new to C programming and I am confused as to how pointers work. How do you use ONLY pointers to copy values for example ... use only pointers to copy the value in x into y.
#include <stdio.h>
int main (void)
{
int x,y;
int *ptr1;
ptr1 = &x;
printf("Input a number: \n");
scanf("%d",&x);
y = ptr1;
printf("Y : %d \n",y);
return 0;
}
It is quite simple. & returns the address of a variable. So when you do:
ptr1 = &x;
ptr1 is pointing to x, or holding variable x's address.
Now lets say you want to copy the value from the variable ptr1 is pointing to. You need to use *. When you write
y = ptr1;
the value of ptr1 is in y, not the value ptr1 was pointing to. To put the value of the variable, ptr1 is pointing to, use *:
y = *ptr1;
This will put the value of the variable ptr1 was pointing to in y, or in simple terms, put the value of x in y. This is because ptr1 is pointing to x.
To solve simple issues like this next time, enable all warnings and errors of your compiler, during compilation.
If you're using gcc, use -Wall and -Wextra. -Wall will enable all warnings and -Wextra will turn all warnings into errors, confirming that you do not ignore the warnings.
What's a pointer??
A pointer is a special primitive-type in C. As well as the int type stored decimals, a pointer stored memory address.
How to create pointers
For all types and user-types (i.e. structures, unions) you must do:
Type * pointer_name;
int * pointer_to_int;
MyStruct * pointer_to_myStruct;
How to assing pointers
As I said, i pointer stored memory address, so the & operator returns the memory address of a variable.
int a = 26;
int *pointer1 = &a, *pointer2, *pointer3; // pointer1 points to a
pointer2 = &a; // pointer2 points to a
pointer3 = pointer2; // pointer3 points to the memory address that pointer2 too points, so pointer3 points to a :)
How to use a pointer value
If you want to access to the value of a pointer you must to use the * operator:
int y = *pointer1; // Ok, y = a. So y = 25 ;)
int y = pointer1; // Error, y can't store memory address.
Editing value of a variable points by a pointer
To change the value of a variable through a pointer, first, you must to access to the value and then change it.
*pointer1++; // Ok, a = 27;
*pointer1 = 12; // Ok, a = 12;
pointer1 = 12; // Noo, pointer1 points to the memory address 12. It's a problem and maybe it does crush your program.
pointer1++; // Only when you use pointer and arrays ;).
Long Winded Explanation of Pointers
When explaining what pointers are to people who already know how to program, I find that it's really easy to introduce them using array terminology.
Below all abstraction, your computer's memory is really just a big array, which we will call mem. mem[0] is the first byte in memory, mem[1] is the second, and so forth.
When your program is running, almost all variables are stored in memory somewhere. The way variables are seen in code is pretty simple. Your CPU knows a number which is an index in mem (which I'll call base) where your program's data is, and the actual code just refers to variables using base and an offset.
For a hypothetical bit of code, let's look at this:
byte foo(byte a, byte b){
byte c = a + b;
return c;
}
A naive but good example of what this actually ends up looking like after compiling is something along the lines of:
Move base to make room for three new bytes
Set mem[base+0] (variable a) to the value of a
Set mem[base+1] (variable b) to the value of b
Set mem[base+2] (variable c) to the sum mem[base+0] + mem[base+1]
Set the return value to mem[base+2]
Move base back to where it was before calling the function
The exact details of what happens is platform and convention specific, but will generally look like that without any optimizations.
As the example illustrates, the notion of a b and c being special entities kind of goes out the window. The compiler calculates what offset to give the variables when generating relevant code, but the end result just deals with base and hard-coded offsets.
What is a pointer?
A pointer is just a fancy way to refer to an index within the mem array. In fact, a pointer is really just a number. That's all it is; C just gives you some syntax to make it a little more obvious that it's supposed to be an index in the mem array rather than some arbitrary number.
What a does referencing and dereferencing mean?
When you reference a variable (like &var) the compiler retrieves the offset it calculated for the variable, and then emits some code that roughly means "Return the sum of base and the variable's offset"
Here's another bit of code:
void foo(byte a){
byte bar = a;
byte *ptr = &bar;
}
(Yes, it doesn't do anything, but it's for illustration of basic concepts)
This roughly translates to:
Move base to make room for two bytes and a pointer
Set mem[base+0] (variable a) to the value of a
Set mem[base+1] (variable bar) to the value of mem[base+0]
Set mem[base+2] (variable ptr) to the value of base+1 (since 1 was the offset used for bar)
Move base back to where it had been earlier
In this example you can see that when you reference a variable, the compiler just uses the memory index as the value, rather than the value found in mem at that index.
Now, when you dereference a pointer (like *ptr) the compiler uses the value stored in the pointer as the index in mem. Example:
void foo(byte* a){
byte value = *a;
}
Explanation:
Move base to make room for a pointer and a byte
Set mem[base+0] (variable a) to the value of a
Set mem[base+1] (variable value) to mem[mem[base+0]]
Move base back to where it started
In this example, the compiler uses the value in memory where the index of that value is specified by another value in memory. This can go as deep as you want, but usually only ever goes one or two levels deep.
A few notes
Since referenced variables are really just numbers, you can't reference a reference or assign a value to a reference, since base+offset is the value we get from the first reference, which is not stored in memory, and thus we cannot get the location where that is stored in memory. (&var = value; and &&var are illegal statements). However, you can dereference a reference, but that just puts you back where you started (*&var is legal).
On the flipside, since a dereferenced variable is a value in memory, you can reference a dereferenced value, dereference a dereferenced value, and assign data to a dereferenced variable. (*var = value;, &*var, and **var are all legal statements.)
Also, not all types are one byte large, but I simplified the examples to make it a bit more easy to grasp. In reality, a pointer would occupy several bytes in memory on most machines, but I kept it at one byte to avoid confusing the issue. The general principle is the same.
Summed up
Memory is just a big array I'm calling mem.
Each variable is stored in memory at a location I'm calling varlocation which is specified by the compiler for every variable.
When the computer refers to a variable normally, it ends up looking like mem[varlocation] in the end code.
When you reference the variable, you just get the numerical value of varlocation in the end code.
When you dereference the variable, you get the value of mem[mem[varlocation]] in the code.
tl;dr - To actually answer the question...
//Your variables x and y and ptr
int x, y;
int *ptr;
//Store the location of x (x_location) in the ptr variable
ptr = &x; //Roughly: mem[ptr_location] = x_location;
//Initialize your x value with scanf
//Notice scanf takes the location of (a.k.a. pointer to) x to know where
//to put the value in memory
scanf("%d", &x);
y = *ptr; //Roughly: mem[y_location] = mem[mem[ptr_location]]
//Since 'mem[ptr_location]' was set to the value 'x_location',
//then that line turns into 'mem[y_location] = mem[x_location]'
//which is the same thing as 'y = x;'
Overall, you just missed the star to dereference the variable, as others have already pointed out.
Simply change y = ptr1; to y = *ptr1;.
This is because ptr1 is a pointer to x, and to get the value of x, you have to dereference ptr1 by adding a leading *.

Value of *ip printed as the address of the variable it is pointing to

For the code below
int main()
{
int x = 2;
int *ip = &x;
printf("%d",*ip); // Printing the value of *ip gives 2
//Now if the value of ip is incremented
ip++;
printf("%d",*ip); //Printing the value of *ip gives the incremented memory
}
Can someone please explain as how the value of *ip is getting printed as the incremented memory location. *ip being the deferencing operator should return the value at the address right?
I see two things wrong with the code. One is the line:
int *ip = x;
This attempts to assign the value of an int to a pointer. This can be forced with compiler flags, but should give an error. Nevertheless, I suspect this may be a typo in your question, since dereferencing an address of 2 should almost certainly crash, but you've claimed it ran and produced an output of 2. I'm going to assume you actually have:
int *ip = &x;
The second problem is:
ip++;
Here you are incrementing the pointer, rather than the int it points to. I think what you intended (to increment 2 to 3) would be:
(*ip)++;
That is, increment the value the pointer points to.
If you increment the pointer, it will now point to somewhere else on your stack, which could be another local variable (like the pointer itself), or the return address, or the stack frame pointer, or some other hidden value. There is a good chance the new value will be some sort of pointer which a value similar to the address of your pointer, or will otherwise look like the output of printing a pointer. Naturally, you should not be incrementing a pointer that points to a single element. It's never a good idea.
This code may behave unpredictably, because
int *ip = x;
assigns the value of x, to a pointer.
Basically it hard codes 2 into the pointer ip.
It may compile with warnings.
It may later lead to memory errors at run time.

why increasing the pointer value by one doesn't allow to set a value at that location?

#include<stdio.h>;
void main(){
int x=10;
int *y=&x+1;
*y=15;
printf("\n Address of x is %u",&x);
printf("\n Value of y is %d",*y);
}
In this code why is value of *y not 15,
in output the value of x=25908 and value of y=25912 ?
I want to know why 15 is not shown as output when i made the value at the next address to x as 15 ?
In your code, by writing
int *y=&x+1;
you're accessing memory which is not allocated to your process (program). It invokes undefined behaviour.
In case, x would have been an array name, and having sufficient memory allocated for the offset (here, the value 1), dereferencing obtained y from this operation would have been legal. But, here, x being a single variable, you cannot expect to access the so-called next address, it is invalid.
That said, to print an address, always use the form
printf("Address is %p\n", (void *)&var);
or similar.
Because the thing that you are doing has undefined behavior. You are writing to an unknown address (address of x + sizeof(int) bytes) and you have no idea what the compilers puts in that address and how it arranges the order of the local variables.
Maybe the parameters that are pushed on the stack on printf call have overriden 15 and maybe anything else has happened.
Note that compiling the same code with different flags and optimization level may cause different result. In other words undefined behavior.
When you do
x= 10;
you have memory allocated to store the value 10 and the memory location is &x so this is the memory which can be accessed by you, accessing unowned memory leads to undefined behavior in this case you are accessing &x + 1 which is not under your control

Resources