I am writing a simple program to make sure I fully understand how pointers in C work as I go through Harvard's CS50. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *a = malloc(sizeof(int));
*a = 5;
printf("the address of pointer a is: %p\n", &a);
printf("the address that a is pointing to is: %p\n", a);
printf("the contents of a are: %i\n", *a);
printf("please enter a new value for a: \n");
scanf("%i", a);
printf("the address of pointer a is: %p\n", &a);
printf("the address that a is pointing to is: %p\n", a);
printf("the contents of a are: %i\n", *a);
int *b = malloc(sizeof(int));
*b = 7;
printf("the address of pointer b is: %p\n", &b);
printf("the address that b is pointing to is: %p\n", b);
printf("the contents of b are: %i\n", *b);
a = b;
printf("setting a = b\n");
printf("the address of pointer a is: %p\n", &a);
printf("the address that a is pointing to is: %p\n", a);
printf("the contents of a are: %i\n", *a);
free(a);
free(b);
}
It compiles w/o issues, but when executed, I get the following error: "* Error in `./address': double free or corruption (fasttop): 0x00000000018b7030 * Aborted"
This problem goes away if I get rid of either the free(a) or free(b) statements, however valgrind reveals a memory leak: "==9626== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1 ==9626== at 0x4C2AB80: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==9626== by 0x4206AD: main (address.c:6)"
I've looked through the other questions here and other websites that mention double free corruption, but still can't figure out quite what the issue is... I have a feeling that the answer is simple, and the issue probably lies in the statement "a = b", however I don't really get why I wouldn't be able to have one pointer point to a memory location that another one is pointing to, and then free the memory taken by both pointers...