Home > front end >  Memory fault when print *pointer
Memory fault when print *pointer

Time:11-10

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;
}

CodePudding user response:

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