I am trying to fill a hashmap of Spritesheets. The data for the Spritesheet is read from a json file.
I am using hashmap.c for the hashmap and cJSON for parsing the json data
The SpriteSheet struct
typedef struct
{
char* name;
char* path;
int width;
int height;
} SpriteSheet;
Example Json Data
"spriteSheets": [
{
"name": "player",
"path": "player.png",
"width": 192,
"height": 64
}
]
The Code
spriteSheetHashMap = hashmap_new(sizeof(SpriteSheet), 0, 0, 0, spriteSheetHash, spriteSheetCompare, NULL, NULL);
cJSON* textureJson = cJSON_Parse(textureJsonString);
cJSON* spriteSheetsJson = cJSON_GetObjectItemCaseSensitive(textureJson, "spriteSheets");
cJSON* spriteSheetJson;
cJSON_ArrayForEach(spriteSheetJson, spriteSheetsJson)
{
char* sheetName = cJSON_GetObjectItemCaseSensitive(spriteSheetJson, "name")->valuestring;
char* sheetPath = cJSON_GetObjectItemCaseSensitive(spriteSheetJson, "path")->valuestring;
int sheetWidth = cJSON_GetObjectItemCaseSensitive(spriteSheetJson, "width")->valueint;
int sheetHeight = cJSON_GetObjectItemCaseSensitive(spriteSheetJson, "height")->valueint;
hashmap_set(spriteSheetHashMap, &(SpriteSheet){
.name=sheetName,
.path=sheetPath,
.width=sheetWidth, .height=sheetHeight,
.spriteHashMap=spriteHashMap
});
}
cJSON_Delete(textureJson);
When I access this in some other file, I get a segmentation fault
SpriteSheet* spriteSheet = hashmap_get(spriteSheetHashMap, &(SpriteSheet){ .name="map" });
printf("%s, %s", spriteSheet->name, spriteSheet->path); // This line causes the segmentation fault
But, If I add the items explicitly, it doesn't segfault and prints the values
hashmap_set(spriteSheetHashMap, &(SpriteSheet){
.name="map",
.path="image.png",
.width=4, .height=8
});
// OR
char* a = "map";
char* b = "image.png";
hashmap_set(spriteSheetHashMap, &(SpriteSheet){
.name=a,
.path=b,
.width=4, .height=8
});
Why is this happening? How can I fix it?