Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

((A)) The following program, written in C, writes data all over the data section

ID: 3736033 • Letter: #

Question

((A)) The following program, written in C, writes data all over the data section, starting from the local variable i. Compile and run the program, then answer the questions. Note that the results vary with different compilers and operating systems, so specify the systems you used. Note the behavior of the while loop. The first statement in the loop (*j=0;) writes a zero to the RAM address stored in variable j. The second statement (j=j-1;) moves the address downward in RAM each time the loop executes. Each step of j moves by a “short integer,” which is 2 bytes (16 bits) long. main() { short i, *j; j = &i; while(1) { *j = 0; j = j-1; } }  
Describe what happens when the program runs. ((B))  Does the program behave differently if we store a nonzero value in the first statement in the while loop? For example, substitute 21845 (in hex, 0x5555, alternating 0s and 1s). Describe what happens. Try another numerical value and describe what happens.

main()  

{  

short i, *j;  

j = &i;

  

while(1)  

{

*j = 0;

j = j-1;  

}

}

Explanation / Answer

I am using CentOS platform. I will explain briefly... After reading this, if you have still any clarifications, please give me comment..

short datatype occupies 2 Bytes of memory. It means the range of short int is –32,768 to 32,767(i.e., -215 to 215-1).

Here we are taking one variable and another pointer. variable can creates two bytes of memory and pointer have no memory. It always depends on another variable.

In this example *j is pointer and i is variable. We are assigning address of "i" to the "j".

In iteration we are assigning value 0. It can store value in that address as well it also copies to i variable. It means both j and i have same memory address.

After that we are decrement 1 value to j. It means we are decrementing sizeof(short) to the "j". If that memory existed, it will executed otherwise we will get error as Segmentation fault.

But definitely we will get Segmentation fault after some iterations.

In quesiton-B, Does the program behave differently if we store a nonzero value in the first statement in the while loop?

It doesn't behave diffrently. j can store value upto short range only. if you any value assign to *j, it's never change it's execution...

for checking memory address check with this example

#include <stdio.h>

main()

{

short i, *j;

j = &i;

while (1)

{

*j = 0x5555;

j = j - 1;

printf("addr: %d ", j);

}

}