0

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.

3
  • 2
    No. It is the size of the pointer. Also why should size_of_points ever change? You should read about the basics of C. Commented Dec 16, 2018 at 18:14
  • Note that the loop doesn't change size_of_int or size_of_points. You pass a pointer to the zeroth element of the allocated array to scanf() which over-writes the variable with whatever integer you type (assuming you type an integer); you never change the amount of allocated memory. Commented Dec 16, 2018 at 19:20
  • ok ok i get that know, but theoretically if I want store more than 8 inputs in points, do i have to use a buffer than, instead of malloc, points[200] or would a realloc be better, so everytime there is no space, add one extra space, if needed Commented Dec 16, 2018 at 19:34

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.