Reputation: 27
I have written this code in which readData takes input and stores the values in a structure and writeData prints the values. I need the struct Color* pointer values to stay in heap memory so that I can access it from the writeData function. For some reason, it retains garbage values upon call to writeData. Can someone please help me figure out why this is happening. Thank you
imageloader.c file:
typedef struct Color
{
uint8_t R;
uint8_t G;
uint8_t B;
} Color;
typedef struct Image
{
Color **image;
uint32_t rows;
uint32_t cols;
} Image;
Image *readData(char *filename)
{
FILE *fp = fopen(filename, "r");
char format[3];
int rows = 0, cols = 0, num = 0;
uint8_t R_int = 0;
uint8_t G_int = 0;
uint8_t B_int = 0;
fscanf(fp, "%s\n %d \n %d\n", format, &rows, &cols, &num);
Color** p = (Color** )malloc(rows *cols * sizeof(Color*));
for(int i =0; i< rows *cols; i++)
{
fscanf(fp, "%d %d %d", &R_int, &G_int, &G_int);
Color* c = (Color *) malloc(sizeof(Color));
c->R = R_int;
c->G = G_int;
c->B = B_int;
p[i] = &c;
}
Image *img = (Image*)malloc(sizeof(Image));
img->image = p;
img->rows = rows;
img->cols = cols;
printf("%d", p[0]->R); //garbage value
return img;
}
void writeData(Image *image)
{
}
}
main function calling readData and writeData
int main(int argc, char **argv)
{
Image *image;
uint32_t rule;
char *filename;
processCLI(argc,argv,&filename);
image = readData(filename);
writeData(image);
freeImage(image);
}
Upvotes: 0
Views: 102
Reputation: 81926
Turning on compiler warnings will help you find errors like this.
$ clang -c -Wall -Wextra main.c
main.c:29:57: warning: data argument not used by format
string [-Wformat-extra-args]
..."%s\n %d \n %d\n", format, &rows, &cols, &num);
~~~~~~~~~~~~~~~~~ ^
main.c:33:32: warning: format specifies type 'int *' but
the argument has type 'uint8_t *' (aka
'unsigned char *') [-Wformat]
fscanf(fp, "%d %d %d", &R_int, &G_int, &G_int);
~~ ^~~~~~
%s
main.c:33:40: warning: format specifies type 'int *' but
the argument has type 'uint8_t *' (aka
'unsigned char *') [-Wformat]
fscanf(fp, "%d %d %d", &R_int, &G_int, &G_int);
~~ ^~~~~~
%s
main.c:33:48: warning: format specifies type 'int *' but
the argument has type 'uint8_t *' (aka
'unsigned char *') [-Wformat]
fscanf(fp, "%d %d %d", &R_int, &G_int, &G_int);
~~ ^~~~~~
%s
main.c:38:14: warning: incompatible pointer types assigning
to 'Color *' (aka 'struct Color *') from 'Color **'
(aka 'struct Color **'); remove &
[-Wincompatible-pointer-types]
p[i] = &c;
^ ~~
Upvotes: 1