Note that there are some explanatory texts on larger screens.

plurals
  1. POHelp with C Pointers
    text
    copied!<p>I have a query with regards to pointers, can someone help explain the following to me?</p> <p>I do understand how the pointers work, however, I ain't too sure as to how overwriting parts of memory from addresses modify the behavior of the program.</p> <p>I will explain the following as much as I can according to what I understand, feel free to critic and enlighten me on my misunderstandings, heres the code chunk:</p> <pre><code>void f(int) ; int main ( int argc, char ** argv ) { int a = 1234 ; f(a); printf("Back to main\n") ; } void g() { printf("Inside g\n") ; } void f (int x) { int a[100] ; memcpy((char*)a,(char*)g,399) ; x = *(&amp;x-1) ; *(&amp;x-1) = (int)(&amp;a) ; // note the cast; no cast -&amp;gt; error // find an index for a such that a[your_index] is the same as x printf("About to return from f\n") ; } //This program, compiled with the same compiler as above, produces the following output: //About to return from f //Inside g //Back to main </code></pre> <p>Ok from what I understand, this is how it goes.</p> <p>The program begin procedurally frorm main(), it assigns a, then goes into f() with a as variable.</p> <p>Inside f():</p> <p>It inits an array a of size 100. Then copies the memory space from g() to the entire a array. So now essentially a[] is g(). x is then assigned to the address of the original a from main() - 1, which I would assume is the address of main(). (I am not sure about this, correct me if I'm wrong)</p> <p>From here onwards, I ain't too sure how it manages to call a[] (the one that is overwritted with g()) or even g(). It just seems to end f() and go back to main().</p> <p>Thanks to whoever can help me out with this!</p> <p>Cheers!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload