0
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!

  1. Declares a function of type void called 'myfunc' with 1 parameter: a ptr to a ptr to a char array 'param'
  2. Defines 'myfunc': returns argument 'param' with a prefixed increment
  3. Defines a ptr to a character array 'string', Allocates 64 bytes of memory to the 'string' ptr
  4. Assigns the string "hello_World" to 'string'
  5. Calls 'myfunc', passes the address of 'string' as an argument, which increments/shifts the address 1 byte up(?).
  6. Same as line 4, now the address is two bytes away
  7. 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?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Evan
  • 19
  • 2
  • 2
    A C quiz that casts the return value of `malloc`? Hmmmmm. – Cody Gray - on strike Jun 18 '14 at 04:41
  • Please proofread? Seriously? – Carey Gregory Jun 18 '14 at 04:45
  • Let me rephrase. "Please pardon my syntax errors as I am just starting out, and if you would be so kind as to point them out that would be incredibly helpful." :) And Cody, the makers of the quiz previously recommended a C++ compiler, so maybe they just avoided implicit casting to lean on the safe side? – Evan Jun 18 '14 at 18:42

2 Answers2

5

The function

void myfunc(char** param){
  ++param;
}

doesn't do what you expect it to. It modifies param locally and has no effect on the value of &string in the calling function. You need to use:

void myfunc(char** param){
  ++(*param);
}

If you want to change what string points to in main.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

And there is a memory leak because malloc(64) is called but never freed.

Sam
  • 91
  • 1
  • 4
  • I know but he asked for why the exercise said to ignore memory leaks. – Sam Jun 18 '14 at 05:06
  • Thanks. So if I wanted to free the memory, I could put the line **free(string);** where the comment is? – Evan Jun 18 '14 at 18:23