C static variables [duplicate] - c

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I've been trying to wrap my head around static variables in C and so I wrote this:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int *pointer;
void stat();
int main()
{
stat();
printf("%i", *pointer);
}
void stat()
{
int c = 2;
pointer = &c;
}
This does work and display 2 in the command line, but I don't understand why.
Doesn't int c cease to exist when the function stat exits? Then what does pointer point to? And how does it retain the value of the integer? Why can I do without making int c static here?

c ceases to exist, but you're still allowed to look at that memory location, and you're getting lucky; the value is still there at that moment-- it hasn't been overwritten by anything else yet.
Your understanding is correct; pointer is pointing at memory you shouldn't be looking at once stat returns.

c as an object ceases to exist.
But your pointer does not cease to exist because it is global.
Your pointer is pointing to the memory address where c was.
It will continue pointing there unless you poi it somewhere else.
But, the content at that address could change if something else is assigned that address or overlaps that in memory later.
I should add that nothing here is a static anything.
The static keyword has special significance and it has a deferent effect depending on the scope in which it is declared.

Related

C are pointers erased after function call ends? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 2 years ago.
I have learned that whenever a function ends, every local variable declared inside of it is erased. That's why we must use malloc when declaring an array.
But when I think about that again when a function ends what is really erased (in case I defined an array) is the pointer to that array and not the array itself, So we could simply solve the former problem by returning the pointer.
Here is a look at my code, why did it work while my professor said "we must use malloc"?
#include <stdio.h>
int * test ()
{
int arr[3]={4,5,6};
return arr;
}
int main() {
printf("Hello, World!\n");
int *arr=test();
printf("%d",arr[1]);
return 0;
}
Edit: I'm working according to the C99 standard if that does make a difference.
Option 1:
Change it to static
static int arr[3]={4,5,6};
Lifetime of a static variable is throughout the program. So we can always create a local static array and return it.
Option 2:
Create a struct
struct wrapper {
int arr[3];
};
The reason this is, array members of structures are deeply copied.

Address of the automatic storage class variable assigned to a local variable of another function [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 4 years ago.
#include <stdio.h>
int* function1(void);
int main()
{
int x = 10;
int *p = function1();
printf("%d\n", *p);
printf("%d\n", p);
}
int* function1(void)
{
int z;
z = 20;
z++;
return &z;
}
Variable 'z' is local to the 'function1', and is not alive after the
'function1' is terminated.
Now to access the value at the memory space of the variable 'z', its
address is returned by the function.
So, even after the termination, will the memory space of the variable
'z' will still be reserved, as the pointer accesses the variable?, in such case what will be the properties of the memory space?
Or What if some-other variable is allocated with the same memory space
of variable 'z'?
Note: GCC compiler of code blocks has compiled the program successfully, without any error and warning.
In general what you do is undefined.
However, on Intel architectures z is on the stack and after return, if you don't call any other function the value will probably still be available because the memory has not yet been reused. As soon as you call another function, the memory will probably be overwritten and so will contain garbage for you.
In general: Don't do this!
The variable z does no longer exist after the function function1 finishes it's execution. In function main you are trying to reference a memory address which has been deallocated after the function's call. This will cause undefined behavior.
When the function call happens, all your local variables will be in stack. During function call, the stack variables can be modified. When the function call returns, the stack pointer is decremented’
Hence, you will be accessing something which is not guaranteed in any way. In programming languages, this is addressed as a case of undefined behaviour, since you are overriding the rules of programming language.
In this case of function, given that you stack frame is still active and not modified by any other code, you might get the same value that you wrote to that address.
But is not guaranteed in anyway and dont assume anything not guaranteed.

why does the following code produce segmentation fault [duplicate]

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 5 years ago.
i tried coping a string to a pointer using strcpy. it causes a segmentation fault.any reason for that.
#include <stdio.h>
#include <string.h>
int main()
{
char *str=NULL;
strcpy(str,"C-DAC");
printf("%s\n",str);
return 1;
}
WHere does your string point to? Nowhere!
That's why you have segmentation fault. You have to either allocate variable on stack as array or define it as pointer and later allocate memory using malloc. When using malloc, don't forget to include "stdlib.h"
Either do this:
char str[6];
strcpy(str,"C-DAC");
or
char *str=malloc(sizeof(*str) * 6);
strcpy(str,"C-DAC");
Computer memory is divided into different segments. A segment for the operating system, for code, for local variables (called a stack), for global variables. Now you are initializing a pointer to NULL which means that the pointer str is now pointing to address 0. That address is simply not available for your program, it's meant for the operating system. In order to protect your system when you try to write that area your program is halted.

Is the compiler placing memory on the heap? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
I don't understand why the following C code works (prints '53'). I thought that int a would be placed on the stack and wiped away as soon as foo() exits. If the compiler is instead placing int a on the heap, is there a way to tell it not to?
#include "stdio.h"
int * foo()
{
int a = 53;
int * b = &a;
return b;
}
int main(void)
{
int * c = foo();
printf("%d\n",*c);
return 0;
}
The integer a is stored on the stack. The reason this works is that function foo returns the address of a and function main dereferences this address to print it before the contents of a's address are overwritten. This program works by accident in this instance. If you want to preserve the value of a for the life of the program you'll either need to apply the static qualifier to a's declaration, or allocate a on the heap.

Returning an address of local variable behaviour [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
input:
#include <stdlib.h>
#include <stdio.h>
int func2(void);
int* func1(void);
int func2(void)
{
int* b;
b = func1();
printf("%d", *b);
printf("%d", *b);
printf("%d", *b);
}
int* func1()
{
int a = 13;
return &a;
}
int main()
{
func2();
}
Output:
13 -1077824828 -1077824828
Can someone explain what happened in the stack and OS? Why the result changed from 13 to garbage after getting the value of the pointer?
Sure.
The result will differ between debug and release (clean).
A local variable is EBP-(some offset) if you look at the assembly.
This means, HIGHER IN STACK, as in "further".
This is the address you return.
Normally it would be untouched if the function just returns. In debug build on some compilers, it would be garbaged on purpose to help you catch the dangling pointer error faster. Now, printf call reuses the same addresses in the stack to pass parameters and for its own local variables (it has some). They will be written to the address emptied by func1 return, thus overwriting whatever is pointed by the address you obtained.
Calling printf creates a new stack frame that overwrites the location previously occupied by a.

Resources