0

My Code:

#include <iostream>
#include <cstdlib>
using namespace std;

int *p;
void fun(int *arr, int n)
{
    p = (int *)malloc(sizeof(int) * (n + 1));
    cout << sizeof(p) / sizeof(int) << " " << sizeof(p) << " " << sizeof(int) << endl;
}

int main()
{
    int n;
    cin >> n;
    int arr[n];
    for (int i = 0; i < n; i++)
        cin >> arr[i];
    fun(arr, n);
    return 0;
}

Input:

4
2 1 4 3

Output:

2 8 4

Expected Output:

5 20 4

The code returns an incorrect value of the size which is being allocated to the array using malloc. I identified this problem when I used memset(p, -1, sizeof(p)))and the array was incorrectly initialized. Please help. Thanks in advance.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Manas Singh
  • 65
  • 1
  • 12
  • 4
    The size of a pointer is the size of the *pointer*, not what it points to. You can easily solve this by *not* having manual and explicit dynamic memory handling, and instead use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector). Especially considering that [variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) is not part of the C++ standard, and is a compiler-specific and non-portable extension. – Some programmer dude Jul 31 '19 at 07:30
  • 3
    And in C++ never use `malloc`. It works for simple types like `int` arrays, but since it *only* allocates memory, if you use it for objects that needs construction that construction won't happen. If you *must* use explicit dynamic allocation (assignment or exercise requirement perhaps) then use `new[]`. Perhaps it's time you invest in [a couple of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) to read? – Some programmer dude Jul 31 '19 at 07:33
  • `sizeof(p) / sizeof(int)` makes no sense. `p` isn't an array object, it's simply a pointer. To which your first expression reduces to simply `sizeof (a_pointer)`. – David C. Rankin Jul 31 '19 at 07:36
  • @Someprogrammerdude That is what I was wondering because I am used to using `memset(arr, 0, sizeof(arr));` for arrays and it works perfectly. Thank You. – Manas Singh Jul 31 '19 at 07:36
  • Relevant: [How to find the 'sizeof' (a pointer pointing to an array)?](https://stackoverflow.com/q/492384/580083). – Daniel Langr Jul 31 '19 at 07:43

1 Answers1

3

Because p is a pointer sizeof(p) will return 8 (or 4 on 32 bit systems). Because that is the size used by p. The memory size used by the structure p points to is another story

Manuel Amstutz
  • 1,311
  • 13
  • 33