Heap data getting overwritten by it's own

0

I'm trying to understand heap memory allocation.

I can't understand how does memory pointed by a gets overwritten in the following code.

int main(){
    char* a = malloc(128);
    strcpy(a, "AAAAAAA");
    printf("a: %p\n", a);
    printf("a: %s\n", a);      // break1
    printf("a: %x%x%x\n", *a, *(a+1), *(a+2));

    free(a);
    char* c;
    c = malloc(100);
    printf("c: %p\n", c);      // break2
    printf("c: %s\n", c);
    printf("c: %x%x%x\n", *c, *(c+1), *(c+2));

    free(c);
    return 0;
}

Output:

a: 0x8971008
a: AAAAAAA
a: 414141
c: 0x8971008
c: 0Xt�0Xt
c: 305874

Note: code compiled with flags -m32 and -g.

Memory content from a-4 onwards, as obtained from gdb:

  1. break1:
    0x00000089 0x41414141 0x00414141
  2. break2:
    0x00000069 0xf7f9c830 0xf7f9c830
c
malloc
heap
asked on Stack Overflow Oct 22, 2017 by Jithin Pavithran • edited Oct 22, 2017 by Jithin Pavithran

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0