I want to allocate some memory to a pointer using a function. Following is the code I have written:
#include <stdio.h>
#include <stdlib.h>
int test( unsigned char **q)
{
*q = (unsigned char *) malloc(250);
if(*q == NULL)
{
printf("\n Error: failed to allocate memory");
return -1;
}
// *q[0] = 10;
// *q[1] = 10;
*q[2] = 10;
return 0; /* Returns 0 on success, non-zero value on failure */
}
int main(void)
{
unsigned char *p;
// printf("\n &p = %u", &p);
int result = test(&p);
// printf("\n p[2] = %d", p[2]);
return 0;
}
If I write something in *q[0]
or *q[1]
, there is no error. But when I try to write something to *q[2]
, it gives "Segmentation fault (core dumped)".
Also I'm getting all data as 0 using p[ ]
except p[0]
.
What is wrong with this code?
Instead of this wrong assignment
*q[2] = 10;
that is due to the operator precedence equivalent to
*( q[2] ) = 10;
and as result the dereferenced pointer q[2] is uninitialized and has indeterminate value. You should write either like
( *q )[2] = 10;
or even just like
q[0][2] = 10;
Another way is to introduce an intermediate variable and use it to initialize elements of the array. For example
char *p = *q;
p[2] = 10;
This allows to escape that kind of errors with pointers.