Consider the following scenario in the programming language C:
void f(char* name, int age){
}
int main(int argc, char* argv[]){
char* name = argv[1];
int x = 1
f(name, x);
}
How would the stackframe of f()
look like in this situation? I'm asking myself if the name is really pushed to the stack, since it is a pointer...
Is the following correct?
---high address---
argv[1]
1
return address
saved EBP
---low address---
Or without argv[1]
?
CodePudding user response:
I'm asking myself if the name is really pushed to the stack
A pointer stores the memory address of what it points to. If you are passing a pointer as an argument to a function, you are passing a copy of such memory address, and thus not the content itself.
void myFunction(char* ptrNameCopy)
{
printf("%p\n", &ptrNameCopy); // "#300", the address of 'ptrNameCopy'
printf("%p\n", ptrNameCopy); // "#100", the copy of 'ptrName' content
printf("%s\n", ptrNameCopy); // "program", the content at address #100, pointed by 'ptrName'
}
int main(int argc, char** argv)
{
char* ptrName = argv[0];
printf("%p\n", ptrName); // "#100", 'ptrName' content
myFunction(ptrName);
return 0;
}
An illustration before returning from myFunction.
at myFunction,
--------- ------------- -------------------------------------
| Address | What | Content |
--------- ------------- -------------------------------------
| #300 | ptrNameCopy | #100 (aka. copy of ptrName content) |
--------- ------------ --------------------------------------
at main,
--------- ------------- --------------------------------
| Address | What | Content |
--------- ------------- --------------------------------
| #100 | argv[0] | "./program" |
| #200 | ptrName | #100 (aka. address of argv[0]) |
--------- ------------- --------------------------------