What I'm basically doing is
- passing a pointer to struct to a function and
- the called function then allocates memory to it by malloc.
Now when I access this memory in Caller function there are no errors.
However if I try to access the same in the called function after allocation.
- there are no errors in accessing first index of array
- But as I try to access the next index of that array it gives segmentation fault
I'm trying to understand what is happening here or am I missing something.
#include <stdio.h>
#include <stdlib.h>
typedef struct _Data
{
int a;
int b;
int c;
} Data_t;
void update(Data_t** ppData)
{
int i;
*ppData = malloc(3 * sizeof(Data_t));
if(*ppData == 0)
{
puts("Error malloc\n");
}
printf("2:Addr = %u %u\n", &ppData, ppData);
#if 1
for(i=0; i < 3; i++)
{
ppData[i]->a = (i+1)*10;
ppData[i]->b = (i+1)*20;
ppData[i]->c = (i+1)*30;
printf("3:[%d] %d %d %d\n", i, ppData[i]->a, ppData[i]->b, ppData[i]->c);
}
#endif
}
int main()
{
Data_t* data;
int i = 0;
printf("1:Addr = %u %u\n", &data, data);
update(&data);
printf("2:Addr = %u %u\n", &data, data);
#if 0
for(i=0; i < 3; i++)
{
data[i].a = (i+1)*10;
data[i].b = (i+1)*20;
data[i].c = (i+1)*30;
printf("4:[%d] %d %d %d\n", i, data[i].a, data[i].b, data[i].c);
}
#endif
for(i=0; i < 3; i++)
{
printf("5:[%d] %d %d %d\n", i, data[i].a, data[i].b, data[i].c);
}
}
stderr, notstdoutWhen the error condition is from a system function, should also output the text that indicates why the system thinks the error occurred. Suggest using:perror( "malloc failed" );which will handly both requirements.malloc()failing, then after displaying the error info viaperror(), should 'cleanup' if necessary, the exit the program. The posted code keeps right on executing the program, as if the call tomalloc()were successful.enumstatement or#definestatements to give those 'magic' numbers meaningful names, then using those meaningful names throughout the code.