I got a segfault error while executing this code. It prints the largest of 5 numbers, and those numbers are stored in heap-memory.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(5 * sizeof(int));
*ptr = 5;
*(ptr + 1) = 7;
*(ptr + 2) = 2;
*(ptr + 3) = 9;
*(ptr + 4) = 8;
int *ptr_max = (int *)malloc(sizeof(int));
*ptr_max = 0;
for (int i = 0; i < 5; i++) {
if (*ptr_max < *ptr) {
*ptr_max = *ptr;
ptr++;
} else
ptr++;
}
printf("%d\n", *ptr_max);
free(ptr);
free(ptr_max);
return 0;
}
I want to know why exactly I got this error from the above code. Please can anyone explain it to me?