#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = NULL;
ptr = (int*)malloc(2*sizeof(int*));//memory allocation dynamically
return 0;
}// What is the error in this type of allocation
Asked
Active
Viewed 150 times
1

digital_revenant
- 3,274
- 1
- 15
- 24

Sahil Mehra
- 21
- 1
-
You are indeed doing something wrong - do you have no idea at all what it is? (Apart from casting the result of `malloc`) – Useless Nov 08 '13 at 10:48
-
1[Do not cast the return of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Eregrith Nov 08 '13 at 10:52
-
I've compiled with gcc, and used *ptr = 34; no error occurs - even though the code is missing strictness. – jacouh Nov 08 '13 at 11:05
3 Answers
2
I guess you want allocate the space for 2 ints (not 2 pointers to int):
int *ptr = malloc(2*sizeof(int));//memory allocation dynamically

Claudio
- 10,614
- 4
- 31
- 71
1
You would have understood that if you read the compilation error carefully.
int *ptr = NULL;
ptr = (int*)malloc(2*sizeof(int*)); //wrong
The above code is wrong. It should be:
ptr = malloc(2*sizeof(*ptr));
No need to cast the return value of malloc
. void *
will be safely casted. Additionally, using sizeof(*ptr)
is easier to maintain in case ptr's data type needs to be modified.
Also, free dynamically allocated memory when its no longer needed or you will have memory leak.
free(ptr);

digital_revenant
- 3,274
- 1
- 15
- 24
-
`sizeof(*ptr)` is not any more portable than `sizeof(int)`. Those are simply correct way compared to original `sizeof(int*)`. – user694733 Nov 08 '13 at 10:59
-
Suppose I change `int *ptr` to `long *ptr`, I do not need to make any changes in allocation. If instead, I had used `sizeof(int)` it would need to be modified to `sizeof(long)`. – digital_revenant Nov 08 '13 at 11:01
-
Yes that is true, but it has nothing to do with how portable the code is. (= does the current code run in other environment without needing to modify it) – user694733 Nov 08 '13 at 11:03
-
1Yes, portable is the wrong word. I should have used ease of maintenance :) – digital_revenant Nov 08 '13 at 11:04
0
The problem lies at sizeof(int*))
and it should be sizeof(int))
Dynamic allocation requires you to tell what size of bytes you want it to allocate, and for that reason in this example you should use sizeof(int)
.

Orel Eraki
- 11,940
- 3
- 28
- 36