0

Below are two chunks of code, and I am not able to figure out why is the output in the following way. In the first code, I use printf to print the returned pointer, so it works right in the main function too, but in the second when I remove the printf statement, it prints something else. And the output changes everytime.

The main function is same for both the cases.

char * updateSlidingWindow(char * slide, char newChar) {
    char * c, dst[strlen(slide)];
    int dstindex = 0;
    c = slide + 1;
    while(*c != '\0')
        dst[dstindex++] = (char)*c++;
    dst[dstindex++] = newChar;
    dst[dstindex] = '\0';
    slide = dst;
    printf("%s\n", slide);  // This line is commented for testing. It changes output.
    return slide;
   }

// main function

int main(void) {
    char * SLIDING_WINDOW = "Hello";
    SLIDING_WINDOW = updateSlidingWindow(SLIDING_WINDOW, 'D');

    printf("%s\n", SLIDING_WINDOW);
    return 0;
}

Output - With printf in update function -

elloD
elloD

Without printf in update function -

����
phraniiac
  • 384
  • 1
  • 3
  • 16
  • 1
    `dst` is a local variable. When it goes out of scope at the end of the function you have a problem. It's undefined behavior. It may appear to work under some circumstances but it's broken code. – Retired Ninja Jul 30 '16 at 03:49
  • 1
    This is relevant as well since it's the same issue in C and C++: http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – Retired Ninja Jul 30 '16 at 03:51

0 Answers0