I was trying to make a symbolic table using C. Below is the excerpt of the code:
#include
#include
#include
#define TYPE_A 0
#define TYPE_C 1
#define TYPE_L 2
typedef struct {
char* symbol;
int address;
} SYMBOLS;
SYMBOLS** addEntry(char* symbol, int line, SYMBOLS** table, int* totalCount) {
SYMBOLS* newEntry = malloc(sizeof(SYMBOLS));
newEntry->symbol = strdup(symbol);
newEntry->address = line;
table[*totalCount] = newEntry;
(*totalCount)++;
return table;
}
SYMBOLS** initSymbol(int capacity, int* totalCount) {
SYMBOLS** table = malloc(sizeof(SYMBOLS*) * capacity);
return table;
}
char* cleanLine(char* d, FILE* fp) {
char* c = strdup(d);
while (*c == ' ' || *c == '/' || *c == '\n') {
if (*c == ' ') c++;
if (*c == '/' || *c == '\n') {
if (fgets(c, 100, fp) == NULL) return NULL;
}
}
char* end = c;
while (*end != '\n') end++;
while (*(end-1) == ' ') end--;
*end = '\0';
return c;
}
int instructionType(char* c) {
if (*c == '(') return TYPE_L;
else if (*c == '@') return TYPE_A;
else return TYPE_C;
}
int main(int argc, char* argv[]) {
if (argc >= 2) {
FILE* fp = fopen(argv[1], "r");
FILE* hack = fopen("test.hack", "w");
char* instruction = malloc(sizeof(char) * 100);
int capacity = 1000;
int* totalCount = malloc(sizeof(int));
*totalCount = 0;
SYMBOLS** table = initSymbol(capacity, totalCount);
printf("asdf\n");
while (fgets(instruction, 100, fp) != NULL) {
instruction = cleanLine(instruction, fp);
printf("%s\n", instruction);
int type = instructionType(instruction);
printf("%d\n", type);
printf("sdfj");
}
}
return 0;
}
However, when I execute this code, it returns malloc(): corrupted top size error. I put some printfs in order to check which part of the code is causing this, and surprisingly, the one which displays the value of type works whereas the subsequent one ("sdfj") doesn't. I don't have the faintest idea why two consecutive printfs don't work correctly.
I think none of valuable are accessing to the outside of allocated memory, and all variables are accessible within main function.
Are there any mistakes?
Here's the file I used for the test:
// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/6/rect/Rect.asm
// Draws a rectangle at the top-left corner of the screen.
// The rectangle is 16 pixels wide and R0 pixels high.
// Usage: Before executing, put a value in R0.
// If (R0 <= 0) goto END else n = R0
@R0
D=M
(The file above is from Nand2Tetris and all rights would be attributed to the project)