Why do I have a memory fault in the below code? How do I fix it?
I want to read the progress of the outside function.
But I only get the output get_report_progress:100
#include <iostream>
int* int_get_progress = 0;
void get_progress(int* int_get_progress)
{
int n = 100;
int *report_progress = &n;
int_get_progress = report_progress;
std::cout << "get_report_progress:" << *int_get_progress <<std::endl;
}
int main()
{
get_progress(int_get_progress);
std::cout << "main get process:" << *int_get_progress << std::endl;
return 0;
}
Your global int_get_progress variable is a pointer that is initialized to null. You are passing it by value to the function, so a copy of it is made. As such, any new value the function assigns to that pointer is to the copy, not to the original. Thus, the global int_get_progress variable is left unchanged, and main() ends up deferencing a null pointer, which is undefined behavior and in this case is causing a memory fault.
Even if you fix the code to let the function update the caller's pointer, your code would still fail to work properly, because you are setting the pointer to point at a local variable that goes out of scope when the function exits, thus you would leave the pointer dangling, pointing at invalid memory, which is also undefined behavior when that pointer is then dereferenced.
Your global variable (which doesn't need to be global) should not be a pointer at all, but it can be passed around by pointer, eg:
#include <iostream>
void get_progress(int* p_progress)
{
int n = 100;
*p_progress = n;
std::cout << "get_report_progress:" << *p_progress << std::endl;
}
int main()
{
int progress = 0;
get_progress(&progress);
std::cout << "main get process:" << progress << std::endl;
return 0;
}
Alternatively, pass it by reference instead, eg:
#include <iostream>
void get_progress(int& ref_progress)
{
int n = 100;
ref_progress = n;
std::cout << "get_report_progress:" << ref_progress << std::endl;
}
int main()
{
int progress = 0;
get_progress(progress);
std::cout << "main get process:" << progress << std::endl;
return 0;
}
Alternatively, don't pass it around by parameter at all, but return it instead, eg:
#include <iostream>
int get_progress()
{
int n = 100;
std::cout << "get_report_progress:" << n << std::endl;
return n;
}
int main()
{
int progress = get_progress();
std::cout << "main get process:" << progress << std::endl;
return 0;
}
Related
Basically I'm wondering what the rules are for passing in pointers vs references to functions in C++. I couldn't find them stated anywhere. Can you pass a primitive type integer, for example, into a function expecting a pointer? Can't you only pass in pointers to methods expecting pointers?
A pointer is just a memory address and in c++ you can get the address of a variable by using the &. Here is an example
#include <iostream>
void increment(int& x)
{
++x;
}
void increment2(int* x)
{
++(*x);
}
int main()
{
int i = 1;
int * p = new int(1);
increment2(&i);
increment2(p);
std::cout << i << std::endl;
std::cout << *p << std::endl;
increment(i);
increment(*p);
std::cout << i << std::endl;
std::cout << *p << std::endl;
}
output
2
2
3
3
try it:
https://godbolt.org/z/br9APq
I'm trying to get the hang of pointers and addresses in C++ and am having trouble with functions with changing parameters.
The code below is writing Loop run #1. in an infinite loop, instead of incrementing the value foo.
My question is: What is the issue with this code here?
#include <iostream>
void Statement(int *foo) {
std::cout << "Loop run #" << *foo << ". ";
foo++;
}
int main() {
int foo = 1;
for (;;) {
Statement(&foo);
}
}
You're incrementing a copy of the pointer itself, not what it points to. You probably meant:
(*foo)++;
This still won't fix the infinite loop though because you have nothing to stop it with.
Your issue is that you're incrementing the pointer, not the pointed-to data.
replace
foo++
with
(*foo)++
to increment the pointed-to value.
If I have understood correctly what you are trying to do then the function should be declared the following way as it is shown in the demonstrative program
#include <iostream>
void Statement(int *foo) {
std::cout << "Loop run #" << *foo << ". ";
++*foo;
}
int main() {
int foo = 1;
for (; ; ) {
Statement(&foo);
}
}
That is in an infinite loop you are trying to output incremented value of foo.
In this case you have increment the value itself pointed to by the pointer like
++*foo
If you want to limit loop iterations then you can use for example an object of the type unsigned char and define the loop the following way
#include <iostream>
void Statement( unsigned char *foo) {
std::cout << "Loop run #" << int( *foo ) << ". ";
++*foo;
}
int main() {
unsigned char foo = 1;
for (; foo ; ) {
Statement(&foo);
}
}
Below is a output question.I am not able to understand why its answer is 30.
#include<iostream>
using namespace std; //namespace std is being used
int &fun()
{
static int x = 10; //x is static
return x;
}
int main()
{
fun() = 30;
cout << fun(); //fun() called
return 0;
}
OUTPUT:30
Can anybody tell why output is coming to be 30 and also can explain the role of static keyword
In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program
void foo()
{
int a = 10;
static int b = 10;
a++;
b++;
std::cout << "a : " << a << " , b : " << b << std::endl;
}
A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.
int a = 4;
int b = a;
int &c = a;
c++;
std::cout << "b = " << b << std::endl; //4
std::cout << "a = " << a << std::endl; //5
std::cout << "c = " << c << std::endl; //5
/* Becaues c is a refence to a, it means that
a and c are just different names to the same memory location
so updating either one updates the actual value in memory
*/
a++;
std::cout << "c = " << c << std::endl; //6
std::cout << "a = " << a << std::endl; //6
//consider the function below:
int &bar()
{
static int a = 5;
std::cout << "a is " << a << std::endl;
return a;
}
Testing the two:
int main()
{
for (int i = 0; i < 3; i++)
foo();
//for every call of foo():
//memory allocation for a is created and deleted when a goes out of scope
//memoery allocation for b extends through out the life of the program
//bar() returns a reference to "a" i.e
int reference_to_a = bar(); //prints 5
reference_to_a = 30;
bar(); //prints 30
bar() = 50; //prints 30 and later assigns 50 to the reference returned.
bar(); //prints 50
}
static make the variable persist across function calls.
which means static int x = 10; will be executed once when func is called for the first time.
int static_test()
{
static int x = 10;
x++;
return x;
}
static_test(); // first call will return 11
static_test(); // second call will return 12 because the value of x ( was saved and was then incremented)
static_test(); // third call will return 13
Now, you need to understand what reference are. To understand what reference are you need to understand pointers. I am guessing you will easily find some website explaining those two.
case 1:
#include<iostream>
using namespace std; //namespace std is being used
int &fun()
{
int x = 10; //x is static
return x;
}
int main()
{
fun() = 30;
cout << fun(); //fun() called
return 0;
}
Here, in the call fun(), we are declaring a local variable int x, which goes out of scope once it returns from fun().
so, in the line cout << fun() a new variable is declared and address of the new variable is returned.
case 2:
static int x = 10;
here, since variable 'x' is static, it can be initialized only once. i.e., the first time x is initialized to 5 and then over written to 30.
now when you are making the function call subsequent times, static int x = 5 is ignored. Hence, it returns the value 30
I have a problem. I want to operate with single element of an array, which is generated in member function, but it doesn´t work. Here is my code:
using namespace std;
class Example
{
public:
int *pole;
void generate_pole();
};
void Example::generate_pole()
{
int *pole = new int [10];
for (int i = 0; i < 10; i++)
{
pole[i] = i;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Example reference;
reference.generate_pole();
cout << reference.pole[1] << endl; //there is the problem
system("pause");
return 0;
}
How can I get an access to the element? And where is the real problem? Thank you!
int *pole = new int [10]; is creating an identically named variable pole in local scope. This is shadowing the member variable.
A fix, drop the int* from the errant line: pole = new int [10];
That said, I'd be inclined to use a constructor to set the member variable in this case: certainly you should initialise pole to nullptr by default. This is so you can delete[] pole in a destructor when an instance of your class goes out of scope. Else your code will leak memory like a colander leaks water.
An other way would be to use std::vector<int> pole; and let the C++ standard library take care of all the memory for you.
The problem is, that you shadow pole's name in the scope of the function by redeclaring it. leave the int * in front of pole behind, in generate_pole, and it should work.
An example for shadowing:
int i = 0; // i is 0
std::cout << "before scope: " << i << std::endl; // prints 0
{
int i = 1;
std::cout << "inside scope: " << i << std::endl; // prints 1
}
std::cout << "behind scope: " << i << std::endl; // prints 0
#include <iostream>
void swap(int &pi, int &pj){
std::cout << "In function swap: " << &pi << " " << &pj << "\n";
int temp = pi;
pi = pj;
pj = temp;
}
int main(){
int i = 10, j = 20;
int *pi = &i, *pj = &j;
swap(pi, pj);
std::cout << *pi << " " << *pj;
return 0;
}
The above program does not give any compilation error. (Though to swap function in not POINTER TO REFERENCE type) and gives the proper output.
But whatever i am trying to print inside "swap" function is not printed to console.
Can anybody explain me why?
Looks like you're probably using std::swap to swap two pointers instead of calling your own swap routine. I suspect you have a using namespace std; somewhere that you are not showing us ? Try changing the name of your swap routine to e.g. my_swap and then see if calling my_swap works (it should fail with a compilation error).
If you can compile your program, you don't show us all of your code.
This code snippet you posted doesn't compile, because you're trying to pass to objects of type int* to your function swapm which expects a reference to an int.
If your code compiles, I suspect you to include a 'using namespace std;' anywhere in your original code.
you're trying to get the address of a pointer that you're passing by reference... I don't think you quite understand what you're doing. the pass by reference feature in C++ allows you to pass a reference, so you don't need a pointer. Your code should look like this.
#include <iostream>
void swap(int &i, int &j){
std::cout << "In function swap: " << i << " " << j << "\n";
int temp = i;
i = j;
j = temp;
}
int main(){
int i = 10, j = 20;
swap(i, j);
std::cout << i << " " << j;
return 0;
}