Im learning the dynamic storage allocation functions and I have a question about why this is happening. I made a function my_malloc that takes my request in bytes as argument and should return a pointer to the block of memory. And I wanted to allocate space for an array of 10 numbers, so it should be 40 bytes right? After the call of my_malloc, when I check the sizeof of the new array it tells me that has 8 bytes, so having a length of 2 elements. When I initialize the array to 100 elements(more than what I asked for) there is no error or something..
Code:
#include <stdio.h>
#include <stdlib.h>
void *my_malloc(int n);
int main(void)
{
int *p, len;
printf("my malloc request: %d bytes\n",(int)(10 * sizeof(int)));
p = my_malloc(10 * sizeof(int));
printf("Values after my_malloc call:\n\n"
"size p: %d bytes\n", (int)sizeof(p));
for(int i = 0; i < 100; i++) //Initializing all elements of p in 1
p[i] = 1;
len = sizeof(p)/sizeof(int);
printf("len: %d\n", len);
for(int i = 0; i < 100; i++) //printing the array
printf("%d ", p[i]);
printf("\n");
len = sizeof(p)/sizeof(int);
printf("len: %d\n", len);
printf("size p: %d bytes\n", (int)sizeof(p));
printf("\n");
return 0;
}
void *my_malloc(int n)
{
void *p = malloc(n);
printf("Values inside my_malloc:\n\n"
"n : %d\n", n);
printf("size p : %d bytes\n\n",(int)sizeof(p));
if (p == NULL) {
printf("malloc failed in my_malloc function.\n");
exit(EXIT_FAILURE);
} else
return p;
}
Can someone please explain me what's happening here? and/or what i'm doing wrong?