C Programming - Memory Allocation - Discussion

Discussion Forum : Memory Allocation - Point Out Errors (Q.No. 1)
1.
Point out the error in the following program.
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *a[3];
    a = (int*) malloc(sizeof(int)*3);
    free(a);
    return 0;
}
Error: unable to allocate memory
Error: We cannot store address of allocated memory in a
Error: unable to free memory
No error
Answer: Option
Explanation:
We should store the address in a[i]
Discussion:
17 comments Page 2 of 2.

Gmdn said:   1 decade ago
Array base address could't never be changed during runtime.

Here "a" is address of array. It can never be changed during runtime.

Instead "*a = malloc" works.

Graeme said:   9 years ago
It should be a = (int *)malloc(sizeof(int*) * 3);

The allocated size should be based on the size of the pointer, not int since the array is of pointers.

Priti Nannavare said:   6 years ago
Array name itself is base address so here they are assigning dynamic allocated memory's address in array name that is in the base address.

Ajit said:   1 decade ago
Even though a[0] means a, that means the above program should allocate address to a[0], then where is the error.

Anand said:   1 decade ago
I don't think their is any error. And 'a' is equivalent to a[0].

Kmokhtar said:   1 decade ago
a[0] does not mean a but it means *(a+0)?

Pavan said:   1 decade ago
Remove the size of 'a' it will work.


Post your comments here:

Your comments will be displayed after verification.