#include<iostream>
using namespace std;
void test(int *s){
s++;
*s=3;
}
int main(){
int s=0;
test(&s);
cout<<s;
return 0;
}
The output I am getting 000. I was expecting only 0. But I am getting zeros equal to value assigned to s in test function. I am not able to understand why is it giving this output?
Edited.
Undefined behaviour is undefined. When called like in your main, test writes through an invalid pointer, so anything can happen.
Your program has undefined behavior.
The line
s++;
increments the pointer, not the value of the object the pointer points to.
and then the line
*s=3;
modified the value at of the new location the pointer points to. That is accessing memory that you are not supposed to access.
You passed &s in test function argument so the *s is the actual value but when you incremented s the pointer went to an undefined location and hence the output could be anything. remove the line s++ and you will get 3 as answer.
Related
This question already has answers here:
Returning an array using C
(8 answers)
Closed 6 months ago.
I wrote a simple c++ program where i am getting a simple float Array from a function. Then I call a function where the generated Array is a parameter of. I print the first value of the Array through the function. It works! BUT when i am declaring another array in the function before i print the value from the first array, the printed value is not the expected one. MAGIC!
CODE THAT DOESN'T WORK:
#include <iostream>;
float* getArray() {
float Array[] = { 4 };
return Array;
}
void compute(float* Array) {
bool newArray[1];
float content = Array[0]; //breakpoint: content will be -107374176.
std::cout << content;
}
int main() {
float* Array = getArray();
compute(Array);
}
OUTPUT: -1.07374e+08
When removing the line "bool newArray[1];" (line 10) the code starts to work.
OUTPUT: 4
Test it your self! Can someone explain me why this happens?
Your main function has a bug. It passes a pointer to Array to compute, which dereferences it. But Array is out of scope at this point since its scope ends when getArray ends. So you are trying to access an object that no longer exists. That is undefined behavior and produces completely unpredictable results.
Arguably, getArray also has a bug since it always returns a pointer to an object that no longer exists. So there is no way to use it. Whether or not that's a bug depends on what the caller is supposed to be able to do with the returned value which cannot be determined due to the lack of comments.
I'm new here!
I'm writing this code for class, and I keep getting a segmentation fault(core dumped) error. Why is this happening?
int main(int argc,char *argv[])
{
char *store[100];int freq[100]={0};int flag;int count=0;int t;
for(int i=0,j=0;i<argc;i++)
{
for(int z=0;z<count;z++)
{
if(*argv[i]==*store[z]) flag=1;t=z;break;
}
if(flag==0) {*store[j]=*argv[i];j++; count++;}
else freq[t]+=1;
flag=0;
}
for(int x=0;x<count;x++) cout<<*store[x]<<"\t"<<freq[x]<<endl;
}
You're accessing an unitialised variable, causing undefined behaviour.(int flag)
In the first iteration count will be equal to 0, so the inner loop will not happen, hence no assignment to flag, before using.
It seems that you want compare *argv[1] with *store[z], but what is the value of *store[z] ?
before using any variable, initialize it ! if it is a pointer, make sure that memory is malloced for it.
char *argv[] and char *store[100] are array of pointers to char, i.e. typically an array of null-terminated strings.
The array store is not initialized, so that, it holds 100 pointers pointing to some undefined memory location.
In line:
if(*argv[i]==*store[z]) flag=1;t=z;break;
you are dereferencing the pointer at index z of array store. As this pointer is undefined, the program typically tries to access a protected memory location. Thus, it segfaults.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
#include <iostream>
#include <string.h>
using namespace std;
/*
The functions defined below are attempting to return address of a local
variable and if my understand is correct...the main function should be
getting garbage.
*/
int *test1(){
int a[2]={1,2};
return a; //returning address of a local variable - should not work.
}
char *test2(){
char a[2]={'a','b'};
return a; //returning address of a local variable - should not work.
}
char *test3(){
char a[1];
strcpy(a,"b");
return a; //returning address of a local variable - should not work.
}
char *test4(){
char a[2];
strcpy(a,"c");
return a; //returning address of a local variable - should not work.
}
int main()
{
int *b= test1();
cout<<*b<<endl; //gives back garbage.
char *c=test2();
cout<<*c<<endl; //gives back garbage.
char *d=test3();
cout<<*d<<endl; //this works - why?
char *e=test4();
cout<<*e<<endl; //gives back garbage.
return 0;
}
As far as my understanding goes regarding function calls and memory management this example program baffles me. If I understand things right, the reason why b=test1() and c=test2() don't work is because they are trying to return address of local variables that are wiped off once the stack memory pops the functions out. But then why is d=test3() working?
You got unlucky because the program failed to blow up.
strcpy(a, "b"); in test3 is fundamentally evil, as there is room for 1 character in a, and strcpy is known to copy the one character in the double quote, plus a termination NUL character, which overwrites memory that your program doesn't really have allocated.
One would advise you to turn your compiler warning levels on the highest level they go. Most compilers will politely give you at least a warning message about it.
The reason why you're third example worked can be summed up as "the phase of the moon was right".
All examples are undefined behaviour, because they return references (or pointers) to local variables. Undefined behaviour means that really anything can happen -- including sometimes the right thingTM, i.e. what you actually meant to happen.
#include<iostream.h>
#include<conio.h>
int *p;
void Set()
{
int i;
i=7;
p=&i;
}
int Use()
{
double d;
d=3.0;
d+=*p;
//if i replace the above 3 statements with --> double d=3.0+*p; then output is 10 otherwise the output is some random value(address of random memory location)
//why is this happening? Isn't it the same?
return d;
}
void main()
{
clrscr();
Set();
cout<<Use();
getch();
}
My question is as mentioned in comments above.I want to know the exact reason for the difference in outputs.In the above code output is some address of random memory location and i understand that is because of i is a local variable of Set() but then how is it visible in the second case that is by replacing it with double d=3.0+*p; because then the output comes 10( 7+3 ) although 7 should not have been visible?
The result of using pointer p is undefined, it could also give you a segfault or just return 42. The technical reason behind the results your'e getting are probably:
i inside Set is placed on the stack. The value 7 ist stored there and p points to that location in memory. When you return from Set value remains in memory: the stack is not "destroyed", it's just the stack pointer which is reset. p still points to this location which still contains the integer representation of "3".
Inside Use the same location on the stack is reused for d.
When the compiler is not optimizing, in the first case (i.e. the whole computation in one line), it first uses the value 7 (which is still there in memory with p pointing to it), does the computation, overwrites the value (since you assign it to d which is at the same location) and returns it.
In the second case, it first overwrites the value withe the double value 3.0 and then takes the first 4 bytes interpreted as integer value for evaluating *p in d+=*p.
This case shows why returning pointers/references to local variables is such a bad thing: when writing the function Set you could even write some kind of unit tests and they would not detect the error. It might get unnoticed just until the software goes into production and has to perform some really critical task and just fails then.
This applies to all kindes of "undefined behaviour", especially in "low level" languages like C/C++. The bad thing is that "undefined" may very well mean "perfectly working until it's too late"...
After exiting function Set the value of pointer p becomes invalid due to destroying local variable i. The program has undefined behavior.
This question already exists:
c++ warning: address of local variable
Closed 9 years ago.
Here is my program
int* fun1(void)
{
int n=9;
int *pf=&n;
cout<<*pf<<endl;
return pf;
}
int main(int argc, char *argv[])
{
int *p=fun1();
cout<<*p;
return 0;
}
Compilation and running of program doesn't give any problems but with valgrind it gives message/warning "Invalid read of size 4".
Any help to resolve the warning is most welcome
nis a local variable in fun1() and is no more valid after exit of the function.
Turning my comment into an answer: You are referencing a local variable from outside of a function after that function has returned. This means that even though, while running the program this seems to work because the stack stays untouched between the assignment. If you call other functions between the assignment and the print, it will most likely fail. I say "most likely" because what you're doing is undefined behavior, and can therefor not be predicted.
To fix this particular case: allocate memory for n on the heap inside fun1, and return a pointer to said memory instead of what you have now.
Local variables exists only when the function is active. You're returning pf which is a pointer to a local variable. As soon as you exit the function, the memory that was allocated to the variable is deallocated, this leads to undefined behavior.
You are returning an address of a local variable and valgrind is warning you of that. Accessing this pointer in the main will invoke undefined behavior.