Below is my program
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
int i;
int* mix_buffer = &i;
int k = 0;
while(1) {
mix_buffer[k]=1;
printf("\n k = %d", k); // 1st printf
printf("\n mix_buffer[%d] = %d k = %d", k, mix_buffer[k], k); //2nd printf
k++;
}
}
When this is compiled with g++
(version 5.4) and run output is
k = 0
mix_buffer[0] = 1 k = 0
Segmentation fault (core dumped)
i.e. segfault occurs after once going through both the printf statements.
However, if I comment the first printf statement in program and recompile, the output is
Segmentation fault (core dumped)
Why does commenting
printf("\n k = %d", k); // 1st printf
cause the program to segfault earlier?