Search code examples
clistmallocuser-inputsizeof

Am I using malloc wrong in this snippet


I'm trying to understand malloc, so I created this little something, to show the sizeof an integer, and the new size given by malloc, but it doesn't increase; it's always 8 bytes for me

So, am I using malloc wrong?

#include <stdio.h>
#include <stdlib.h>

int main() {

    int *points = (int *) malloc(10*sizeof(int));
    int size_of_points = sizeof(points);
    int size_of_int = sizeof(int);

    printf("size of int: %d\n", size_of_int);
    printf("size of points: %d\n\n", size_of_points);

    for ( int counter = 0; counter < size_of_points; counter++) {
        printf("Please enter: ");
        scanf("%d", points);

        printf("**New size of int: %d\n**", size_of_int);
        printf("New size of points: %d\n\n**", size_of_points);
    }

    free(points);

    return 0;
}

At any point, shouldn't size of points be: sizeof(int) is 8 times 10 = 40? It stops with 8 inputs.


Solution

  • There's nothing wrong with your code. What is wrong however, is your understanding: sizeof(some_pointer) always return the size of the pointer, not the size of the chunk of memory pointed to. There's no memory chunk size information in a pointer.