memory allocated to static variables in C [duplicate] - c

This question already has an answer here:
Static variable with the same name in different file [duplicate]
(1 answer)
Closed 2 years ago.
int a, b, c = 0;
void prtFun(void);
int main()
{
static int a = 1; /* line 1 */
prtFun();
a += 1;
prtFun();
printf("\n %d %d ", a, b);
}
void prtFun(void)
{
static int a = 2; /* line 2 */
int b = 1;
a += ++b;
printf(" \n %d %d ", a, b);
}
The output to the above program is:
4,2
6,2
2,0
The local variables are generally stored in the stack of the function and the global variables and the static variables are stored in the data segment of the process right? in that case does having the same static variable name in multiple functions cause any conflicts? how are variables referred to in the data segment?

First of all when you ask the question format your code correctly
int a, b, c = 0;
void prtFun (void);
int main(void)
{
static int a = 1; /* line 1 */
prtFun();
a += 1;
prtFun();
printf ( "\n %d %d " , a, b) ;
}
void prtFun (void)
{
static int a = 2; /* line 2 */
int b = 1;
a += ++b;
printf (" \n %d %d " , a, b);
}
prtFun
b is an automatic variable and it is initialized every time you call this function.
a is static local variable and it is initialised only once and it keeps its value between the function calls. But its scope is local to the function prtFun
So when you call it first time a is assigned 4 and b is assigned 2. You print this values
in function main another a static local variable is assigned value of 2 (initialization + increment).
when you call the prtFun again you add 2 to the function own a variable which keeps the value from the previous call (4) and the result is 6. The b is initialized again to 1 and pre-incremented - so it 2.
Then in function main you print its own a variable (which is 2) and global variable b which is 0

Related

behaviour of function parameters in c programming

So I was casually doing my usual theory proving code (testing things with code) and those code differences really got me thinking
#include <stdio.h>
int mutate(int a){
a+=1;
printf("%d\n", a);
}
void main(){
int b = 1;
mutate(b);
printf("%d", b);
}
and
#include <stdio.h>
int mutate(int *a){
*a+=1;
printf("%d\n", *a);
}
void main(){
int b = 1;
mutate(&b);
printf("%d", b);
}
Why in the first code there's a change without pointers in the first place.? Why there is a temporary change? The code with pointers I already understand though. Could someone explain though?
You use two different ways to pass parameters.
The first implementation of the mutate function uses call by value where a copy of the input parameter is created on the stack which is locally modified as you see in your print result. The value of the original input variable remains unmodified.
The second uses call by reference where a reference to the input variable is given and hence the input variable's value gets modified.
For a nice explanation see https://en.wikipedia.org/wiki/Evaluation_strategy, it also contains the following example which is extremely close to what you are doing:
void modify(int p, int* q, int* r) {
p = 27; // passed by value: only the local parameter is modified
*q = 27; // passed by value or reference, check call site to determine which
*r = 27; // passed by value or reference, check call site to determine which
}
int main() {
int a = 1;
int b = 1;
int x = 1;
int* c = &x;
modify(a, &b, c); // a is passed by value, b is passed by reference by creating a pointer (call by value),
// c is a pointer passed by value
// b and x are changed
return 0;
}
Now your example with output:
#include <stdio.h>
void mutate1(int a) {
a+=1;
printf("value of a inside mutate1: %d\n", a);
}
void mutate2(int *a){
*a+=1;
printf("value of *a inside mutate2: %d\n", *a);
}
int main(){
int b = 1;
printf("value of b before mutate1: %d\n", b);
mutate1(b);
printf("value of b after mutate1: %d\n\n", b);
b = 1;
printf("value of b before mutate2: %d\n", b);
mutate2(&b);
printf("value of b after mutate2: %d\n", b);
return 0;
}
$ gcc -Wall mutate.c
$ ./a.out
value of b before mutate1: 1
value of a inside mutate1: 2
value of b after mutate1: 1
value of b before mutate2: 1
value of *a inside mutate2: 2
value of b after mutate2: 2
$
As can be observed b does not get modified when using call by value but it does when using call by reference.

How to call a global variable in to function in C?

I'm starting at the word of programming so I'm reading a book about programming in C, it says that if I want to call a global variable into a function I need to call the global variable with (::) before the name... in terminal shows this:
funcion2.c:17:57: error: expected expression before ‘::’ token
17 | printf("value of global variable is %d\n",::k);
thaks.
#include <stdio.h>
void f1(void);
int K=5;
void main()
{
int I;
for(I=1; I<=3; I++)
{
f1();
}
void f1(void)
{
int k=2;
K+=K;
printf("VALUE IS: %d\n",k);
::K=::K+K; // <-
printf("VALUE IS %d\n",::k); // <-
}
}
The global variable is called before the main() function, and that beeing said, heres an example of programm using global variable in main() and in funtions:
#include<stdio.h>
void func_1();
void func_2();
int a, b = 10; // declaring and initializing global variables
int main()
{
printf("Global a = %d\n", a);
printf("Global b = %d\n\n", b);
func_1();
func_2();
// signal to operating system program ran fine
return 0;
}
void func_1()
{
printf("From func_1() Global a = %d\n", a);
printf("From func_1() Global b = %d\n\n", b);
}
void func_2()
{
int a = 5;
printf("Inside func_2() a = %d\n", a);
}
Output:
Global a = 0
Global b = 10
From func_1() Global a = 0
From func_1() Global b = 10
Inside func_2() a = 5
In line 4, a and b are declared as two global variables of type int. The variable a will be automatically initialized to 0. You can use variables a and b inside any function. Notice that inside function func_2() there is a local variable with the same name as a global variable. When there is a conflict between the global variable and local variable, the local variable gets the precedence, that's why inside the func_2() value of local variable a is printed.
Unlike local variables, global variables are not destroyed as soon as the function ends. They are available to any function until the program is executing.

Scope of a pointer in memory

I have been studying C for the past weeks, but I can't fully understand how memory manages pointers.
My question arises from this example obtained from here(page 17 of 19): C-Pointer-Basics
Example code:
#include <stdio.h>
void F(int, int *);
int main()
{
int m = 3;
int n = 5;
F(m, &n);
printf("main: %d, %d\n", m, n); // print 3 7 (Where does the 7 came from?)
return 0;
}
void F(int a, int *b)
{
/*
* `a` being a local variable, gets cleaned after `F()` ends
* BUT how does `b` retain the value of `&a`?
*/
a = 7;
*b = a; // `*b = 7`
b = &a; // `b` points to `a`
*b = 4; // `a = 4` and why `*b` doesn't return 4?
printf("F: %d, %d\n", a, *b); // print 4 4
}
The question here is:
Why when main() prints the values of m and n, It showsm = 3 and n = 7?
My assumptions:
As I know, a pointer goes beyond the scope of the function where it is declared, so in void F(int a, int *b) when the function is no longer needed, it gets destroyed, same with his parameters, BUT the value of int *b remains in memory right(even though int *b no longer exists)? So if this is true, we can 'recover' it from memory and use it in main().
Best,
For the question why m and n print 3,7 is because the first parameter is passed by value hence it is only getting copied, therefore no modification of the original m is happening and in the case of n, you're passing its address so when you do *b=a the value of a gets copied to n. And then when you do b=&a the pointer b now starts pointing to the address of a instead of that of n. Which is why the second time you do *b=4, you are not modifying n but a.

Trouble visualizing the stack and heap

I apologize if this is too much code to post, I will delete this if that it is the case. My code below compiles and runs fine but I am unsure if I am allocating memory in the correct spots. Particularly, task 7 and 8. Task 7 should be an array of 10 pointers allocated on the
stack with each pointer referring to 10 unique instances allocated on the heap. Task 8 should be a single pointer allocated on the stack with the pointer referring to an array of 10 instances allocated on the heap. I feel like I have done task 7 and 8 backwards. As you can probably tell this is an assignment and I'm not looking for direct answers. I would just like to know if I'm on the right track for task 7 and 8.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
/* Task 1 -- add typedef and rename to Point3d */
typedef struct POINT_3D
{
int x_cord;
int y_cord;
int z_cord;
} Point3d;
/*Add function prototypes here*/
void init_Point1(Point3d* pt);
Point3d init_Point2(Point3d pt);
void PrintPoint1 (Point3d *pt);
void PrintPoint2(Point3d pt);
int main()
{
int i;
Point3d pt1;
/* Task 2 -- using proper operator give values (5,4,2) to pt1
and use the proper Print function to print it */
pt1.x_cord = 5;
pt1.y_cord = 4;
pt1.z_cord = 2;
printf("Printing Point3d:");
PrintPoint1(&pt1);
/*Task 3 -- Declare a pointer of type Point3d named ptr1*/
Point3d *ptr1;
/*Task 4 -- Allocate memory for ptr1 and initialize it by
calling init_Point1() function and use the proper Print function to print it */
ptr1 = (Point3d*) malloc(sizeof(Point3d));
init_Point1(ptr1);
printf("Printing Point3d:");
PrintPoint1(ptr1);
//Declaring second variable pt2
Point3d pt2;
/*Task 5 and 6 -- Compelete init_Point2 function and
call it with pt2 to create a point with random coordinates)
, use the proper Print function to print it*/
init_Point2 (pt2);
printf("Printing Point3d:");
PrintPoint2(pt2);
/************************************************/
/*************** Part 2 *************************/
/************************************************/
/* All three variables p1, p2, and p3 are intended to be used as *
* some form of array of the struct type declared above. */
Point3d p1[SIZE];
Point3d* p2[SIZE];
Point3d* p3;
printf ("Calling init_Point1()\n");
for (i = 0 ; i < SIZE; ++i)
{
printf ("For position %d\n", i);
init_Point1 (&p1[i]);
PrintPoint1(&p1[i]);
//PrintPoint2(p1[i])
}
/*Task 7 -- Repeat the same steps for array p2, you must call a
proper init function and display the results by calling Print function */
/***********************************/
/* p2 : Declare, Initialize, Print */
/***********************************/
printf ("Calling init_Point1()\n");
for ( i = 0; i < SIZE; i++)
{
p2[i] = (Point3d*) malloc(sizeof(Point3d));
printf ("For position %d\n", i);
init_Point1 (p2[i]);
PrintPoint1 (p2[i]);
}
/* Task 8 -- p3 is a single pointer that must refer to an array of 10 instances
allocated on the heap. Repeat the previous steps for p3 by initializing and
printing using proper functions*/
/***********************************/
/* p3 : Declare, Initialize, Print */
/***********************************/
p3 = (Point3d*) malloc(sizeof(Point3d)*SIZE);
printf ("Calling init_Point1()\n");
for ( i = 0; i < SIZE; i++)
{
printf ("For position %d\n", i);
init_Point1 (&p3[i]);
PrintPoint1 (&p3[i]);
}
return 0;
}
/************************/
/* function definitions */
/************************/
void init_Point1 (Point3d *pt)
{
pt->x_cord = rand() % 100;
pt->y_cord = rand() % 1000;
pt->z_cord = rand() % 100;
}
/* Task 5 - write init_Point2() function definition */
Point3d init_Point2 (Point3d pt)
{
pt.x_cord = rand() % 100;
pt.y_cord = rand() % 1000;
pt.z_cord = rand() % 100;
return pt;
}
void PrintPoint1 (Point3d *pt)
{
printf("\t(x %d , y %d , z %d ) \t", pt->x_cord, pt->y_cord, pt->z_cord);
printf("\n");
}
void PrintPoint2 (Point3d pt)
{
printf("\t(x %d , y %d , z %d ) \t", pt.x_cord, pt.y_cord, pt.z_cord);
printf("\n");
}

C: uninitialized local variable takes on unexpected value [duplicate]

This question already has answers here:
What happens to a declared, uninitialized variable in C? Does it have a value?
(9 answers)
Closed 6 years ago.
I'm really confused about the result of the following code:
#include <stdio.h>
#include <stdlib.h>
int one(int a, int b) {
int k, t;
k = a - b;
t = a + b + 1;
if (k % 2 == 0) return t;
else return 0;
}
int two(int x, int y) {
int m;
printf("%d\n", m);
return m + x + y;
}
main() {
int result = two(5, one(4, 3));
// printf("%d\n", one(4, 3));
printf("result is %d\n", result);
}
one(4, 3) returns 0, which is not surprising. But I don't understand why two(5, 0) returns 8. In other words, m takes on the value 3 without being initialized. How did this happen?
C does not automatically initialize values to 0 when you define them. Technically, reading that data before you initialize it is undefined behavior. In practice, this normally results in a garbage value containing whatever data was stored in that location previously.

Resources