Recorded data from pointer are deleted alone

-1

This question is about C, pointers and gcc. My program writes the number 10 in 5 positions adjacent to the address pointed by the variable num. Apparently those 10's are recorded correctly but only for a while. When I do the second FOR and try to see the values of the previously recorded positions I do not see the 10's I recorded. Why? Who is erasing those 10's? The garbage collector?

Code

void main( void ) {
  int num = 10;
  int *pnum = #

  for( int i=0; i < 5; i++ ) {
    pnum = pnum - 1;
    *pnum = 10;

    printf( "\n%p, %d", pnum, *pnum );
  }

  puts( "===========================" );

  int *p = &num;

  for( int i = 0; i < 5; i++ ) {
    p = p - 1;
    printf( "\n%p, %d", p, *p );
  }
}

Output

  

0xffffcbec, 10
  0xffffcbe8, 10
  0xffffcbe4, 10
  0xffffcbe0, 10
  0xffffcbdc, 10
  =============================   0xffffcbec, 1
  0xffffcbe8, -2146187872
  0xffffcbe4, 0
  0xffffcbe0, 0
  0xffffcbdc, 0

    
asked by Fredy Cuenca 12.09.2017 в 22:39
source

1 answer

0
int num = 10;
int *pnum = &num;

Where is num found? On the stack? In some specific region of memory? In a system registry?

Well, let's suppose that it is in the stack ... when doing the first loop you will be overwriting positions of the stack that do not correspond to the variable (you will step on memory of other variables of your application). It is even possible that you try to write outside the memory assigned to your application and then it will be the Operating System that kills your application to protect the integrity of the memory.

Now suppose that it is a region of memory ... the behavior will be indeterminate depending on the particular conditions of that region of memory ... but the results will be, in general terms, the same as in the case of the pile.

And now we are going to put in the case that it is a record of the processor ... Where will point then pnum-1 ? To another record perhaps ?, To a region of memory? ...? In the event that you point to another record, it will be the execution cycle itself that modifies those variables but do not complain if you start having erratic behaviors.

So good, in short, do not those things under any circumstances. Treat the variables with respect and care. If a variable is not an array or a structure do not iterate on it (and the latter only rarely, such as when dumping its contents into a binary file).

    
answered by 13.09.2017 в 11:15