-1

Here is my code:

int newSize = size + 1; //lets say size = 0
char * newArray = malloc(newSize * sizeof(char));
printf("%li", sizeof(newArray)); //Should be 1, prints 8
printf("%li", newSize * sizeof(char)); //Should be 1, prints 1

I have no clue why it's doing this, but I need newArray to have exactly newSize number of char spots. Any ideas?

Nikhil Jindia
  • 121
  • 1
  • 10
  • 6
    `sizeof(newArray)` is the size of the pointer, not what it points to. – Barmar Nov 21 '19 at 03:38
  • 3
    There's no way to find out the size of what a pointer points to. – Barmar Nov 21 '19 at 03:38
  • 1
    What problem are you trying to solve? `malloc()` is guaranteed to allocate as much space as you request, unless it returns `NULL`. – Barmar Nov 21 '19 at 03:40
  • 1
    It might allocate more, because all allocations need to be aligned for the largest datatype. But the excess space isn't detectable and shouldn't be a problem. – Barmar Nov 21 '19 at 03:41

1 Answers1

1

Because newArray is a pointer sizeof(newArray) gives you the size of the pointer, not the size of the buffer it points to.

When allocating memory you need to keep track of the size of that memory yourself as the language does not give you a way to find that out.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • But is there a way to allocate exactly x characters worth of space instead of always 8, given that I know what x is? – Nikhil Jindia Nov 21 '19 at 03:42
  • 2
    @NikhilJindia What makes you think it allocated 8? That's not the amount of space that was allocated. – Barmar Nov 21 '19 at 03:42
  • You are allocating 1 character. The 8 is the size of the variable `newArray`, which holds a pointer. – Tordek Nov 21 '19 at 03:42
  • When I try to fwrite it to a file it prints the 4 characters it should print then 4 of "^@" – Nikhil Jindia Nov 21 '19 at 03:43
  • @NikhilJindia You *did* allocate 1 character in this case. What you're trying to do to determine the size won't work as you expect. – dbush Nov 21 '19 at 03:43
  • @NikhilJindia don't use `sizeof(newArray)` when writing to the file, either. It's not meaningful at all. – Barmar Nov 21 '19 at 03:44
  • 1
    @NikhilJindia Then you're not correctly keeping track of how many characters to print. – dbush Nov 21 '19 at 03:44
  • Yep, that was the issue, I used sizeof() for the fwrite, I think it's fixed now I'll check Edit: It's working! Thanks so much! Totally brainfarted on the sizeof thing (still trying to learn this language lol) – Nikhil Jindia Nov 21 '19 at 03:45
  • There's no *portable* way, but some malloc implementations can tell you how much space was allocated (which might be more then requested)... glibc's [`malloc_usuable_size()`](http://man7.org/linux/man-pages/man3/malloc_usable_size.3.html) for example. – Shawn Nov 21 '19 at 03:48
  • My prof isn't letting us use any libs other than stdlib stdio sys/time and sys/stat but it's working now – Nikhil Jindia Nov 21 '19 at 03:51