1 void myfunc(char** param){
2 ++param;
}
int main(){
3 char* string = (char*)malloc(64);
4 strcpy(string, "hello_World");
5 myfunc(&string);
6 myfunc(&string);
7 printf("%s\n", string);
// ignore memory leak for sake of quiz
8 return 0;
}
What should the program print?
A) hello_world
B) ello_world
C) llo_world
D) lo_world
E) Illegal memory access, undefined behavior
My dissection, line by line. Please proofread, I just started learning C a few weeks ago and pointers/memory management is starting to "click" in my brain!
- Declares a function of type void called 'myfunc' with 1 parameter: a ptr to a ptr to a char array 'param'
- Defines 'myfunc': returns argument 'param' with a prefixed increment
- Defines a ptr to a character array 'string', Allocates 64 bytes of memory to the 'string' ptr
- Assigns the string "hello_World" to 'string'
- Calls 'myfunc', passes the address of 'string' as an argument, which increments/shifts the address 1 byte up(?).
- Same as line 4, now the address is two bytes away
- ANSWER- It's a trick question; although the address of 'string' was manipulated, the printf function was passed an actual string, not a pointer. Therefore, the output is simply: hello_World
Now, a couple questions. How would one change this code so that b), c), d), or even e) be the correct answer? Also, is the memory leak they're talking about due to the fact that there are 2 "unfreed" bytes of memory after the null character, because the pointer was shifter over 2 bytes? If not, what do they mean?