Why can't I use pointer addition instead of malloc

Viewed 177

I was wondering why I have to use malloc to dynamically create memories, while I already have pointer addition to freely manipulate the memories. So I created this code, but this code corrupts, saying that 'stack around the variable 'a' was corrupted'

Can someone explain why this code fails?

#include <stdio.h>

int main(void)
{
    int a = 1;
    int * arr1 = &a;
    *(arr1 + 1) = 2;
    printf("%d %d\n", *arr1, *(arr1+1));
}
4 Answers
Related