Thu, 02 Dec 2010 17:12:28 +0000
Fix mallocing issue with ram array
RAM storage array was not being correctly allocated at startup. This caused memory access issues... Spotted with Valgrind, fixed.
1 #define _STATE_C
2 #include <stddef.h>
3 #include <malloc.h>
4 #include <stdio.h>
5 #include "state.h"
7 int state_init(size_t ramsize)
8 {
9 // Free RAM if it's allocated
10 if (state.ram != NULL)
11 free(state.ram);
13 // Initialise hardware registers
14 state.romlmap = false;
16 // Allocate RAM, making sure the user has specified a valid RAM amount first
17 // Basically: 512KiB minimum, 4MiB maximum, in increments of 512KiB.
18 if ((ramsize < 512*1024) || ((ramsize % (512*1024)) != 0))
19 return -1;
20 state.ram = malloc(ramsize);
21 if (state.ram == NULL)
22 return -2;
23 state.ram_size = ramsize;
25 // Load ROMs
26 FILE *r14c, *r15c;
27 r14c = fopen("roms/14c.bin", "rb");
28 // if (r14c == NULL) FAIL("unable to open roms/14c.bin");
29 r15c = fopen("roms/15c.bin", "rb");
30 // if (r15c == NULL) FAIL("unable to open roms/15c.bin");
32 // get ROM file size
33 fseek(r14c, 0, SEEK_END);
34 size_t romlen = ftell(r14c);
35 fseek(r14c, 0, SEEK_SET);
36 fseek(r15c, 0, SEEK_END);
37 size_t romlen2 = ftell(r15c);
38 fseek(r15c, 0, SEEK_SET);
39 // if (romlen2 != romlen) FAIL("ROMs are not the same size!");
40 // if ((romlen + romlen2) > ROM_SIZE) FAIL("ROMs are too large to fit in memory!");
42 // sanity checks completed; load the ROMs!
43 uint8_t *romdat1, *romdat2;
44 romdat1 = malloc(romlen);
45 romdat2 = malloc(romlen2);
46 fread(romdat1, 1, romlen, r15c);
47 fread(romdat2, 1, romlen2, r14c);
49 // convert the ROM data
50 for (size_t i=0; i<(romlen + romlen2); i+=2) {
51 state.rom[i+0] = romdat1[i/2];
52 state.rom[i+1] = romdat2[i/2];
53 }
55 // TODO: if ROM buffer not filled, repeat the ROM data we read until it is (wraparound emulation)
57 // free the data arrays and close the files
58 free(romdat1);
59 free(romdat2);
60 fclose(r14c);
61 fclose(r15c);
63 return 0;
64 }
66 void state_done()
67 {
68 if (state.ram != NULL) {
69 free(state.ram);
70 state.ram = NULL;
71 }
72 }