- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can a local variable's memory be accessed outside its scope in C/C++?
Let us look at an example where you MIGHT be able to access a local variable's memory outside its scope.
Example
#include<iostream> int* foo() { int x = 3; return &x; } int main() { int* address = foo(); cout << *address; *address = 12; cout << *address; }
Output
This might give the output −
3 12
As I've mentioned before, this code MIGHT work. We are simply reading and writing to memory that USED to be the address of x. In main, you're outside of foo's scope, the address is a pointer to some random memory area. In the above example, that memory area does exist and nothing else is using it at the moment. You don't break anything by continuing to use it(you won't be using another process' memory area or any other unauthorized memory area), and nothing else has overwritten it yet. Hence, the 3 is still there.
In a real program, that memory might have been re-used almost immediately and you'd break something by something like doing this. Such memory access bugs are very difficult to track and kill.
When you return from foo, the program tells the OS that x's memory is no longer being used and it can be reassigned to something else. If you're lucky and it gets reassigned, and the OS doesn't catch you using it again, then you can get away with it.
- Related Articles
- Can private methods of a class be accessed from outside of a class in Java?
- Explain scope of a variable in C language.
- What is a structure at local scope in C language?
- Write a structure in local scope program using C language
- C# Multiple Local Variable Declarations
- What are the local and global scope rules in C language?
- How can I get a file's size in C++?
- Can a C++ variable be both const and volatile?
- Can one's pride be positive too?
- How Facebook's Metaverse can be a privacy nightmare?
- Can super class reference variable hold sub class's object in java?
- Can a Java array be declared as a static field, local variable or a method parameter?
- What is the scope of an internal variable of a class in C#?
- PHP Variable Scope
- Why can't variables be declared in a switch statement in C/C++?
