When I run the below code, I get the given output.
#include <stdio.h> /* printf */
#include <stdlib.h> /* malloc, realloc */
int main()
{
char* characters = (char *) malloc(10 * sizeof(char));
printf("Before: characters at %p, size=%lu\n", (void *) characters, sizeof(characters) / sizeof(characters[0]));
char* temp = (char *) realloc(characters, 100);
if (temp)
{
printf("After realloc, characters size = %lu, temp size = %lu\n", sizeof(characters) / sizeof(characters[0]), sizeof(temp) / sizeof(temp[0]));
printf("After realloc, nums at %p, temp at %p\n", (void *) characters, (void *) temp);
//characters = temp;
free(temp);
}
free(characters);
}
/* Output:
Before: characters at 0x107b00900, size=8
After realloc, characters size = 8, temp size = 8
After realloc, nums at 0x107b00900, temp at 0x107b00910
test(3556) malloc: *** error for object 0x107b00900: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
*/
I'm trying to figure out what is malfunctioning.
I think that malloc sets aside space for ten consecutive characters and gives me a pointer to the first element of that array, and I store that pointer in characters
. I then print the size of characters
, and I expect 10, but I get 8. That's the first weird thing. Then, I ask realloc to find a new spot in the heap, which has space for 100 consecutive characters and return to me a pointer to the first spot. I put that pointer into temp. When I print temp
's size, I get 8 (again), even though I expect 100. When I print the pointers to characters
and temp
, I get two different locations in the heap. Usually, I would then reassign the characters
pointer to point to whatever temp
is pointing to. Then I tried to free my pointers, and it told me that it couldn't free 0x107b00900
, the exact location characters
is, because the object at that point wasn't malloc
ed; however, I did malloc
space for characters
. Why is this happening? Am I misunderstanding the functionality of malloc
, realloc
, sizeof
, or something else? Thank you for your help.