Improve memory management

This commit is contained in:
Augusto Gunsch 2020-10-29 22:06:33 -03:00
parent 94f12e1006
commit 9c5b35ebf5
No known key found for this signature in database
GPG Key ID: F7EEFE29825C72DC
4 changed files with 29 additions and 7 deletions

View File

@ -1,6 +1,6 @@
FILES = parser.c main.c
INCLUDES = -I.
CFLAGS = -std=c99 -g
CFLAGS = -std=c99
OUTFILE = vmtranslator
main: ${FILES}

9
main.c
View File

@ -16,11 +16,15 @@ int main(int argc, char* argv[]) {
return errno;
}
// info gathering
int lncount, widestln, maxtokens;
getinfo(input, &lncount, &widestln, &maxtokens);
// parsing
struct line** lns = parse(input, lncount, widestln, maxtokens);
fclose(input);
printf("lns: %i\n", lncount);
// printing
for(int i = 0; i < lncount; i++) {
int tkcount = lns[i]->tokenscount;
for(int j = 0; j < tkcount; j++) {
@ -29,5 +33,8 @@ int main(int argc, char* argv[]) {
printf("\n");
}
// freeing
freelns(lns, lncount);
return 0;
}

View File

@ -4,6 +4,18 @@
#include <string.h>
#include "parser.h"
void freelns(struct line** lns, int lnscount) {
for(int i = 0; i < lnscount; i++) {
int tkcount = lns[i]->tokenscount;
for(int j = 0; j < tkcount; j++) {
free(lns[i]->tokens[j]);
}
free(lns[i]->tokens);
free(lns[i]);
}
free(lns);
}
void gountilbrk (FILE* input) {
char c;
while(c = fgetc(input), c != -1) {
@ -23,9 +35,13 @@ void getinfo(FILE* input, int* lncount, int* widestln, int* maxtokens) {
int maxtoks = 0;
short readsmt = 0;
while(c = fgetc(input), c != -1) {
if(isspace(c) && readsmt) {
tokens++;
if(c == '\n') {
currsz++;
if(isspace(c)) {
if(readsmt) {
tokens++;
readsmt = 0;
}
if(c == '\n' && tokens > 0) {
lns++;
if(currsz > widest)
widest = currsz;
@ -34,7 +50,6 @@ void getinfo(FILE* input, int* lncount, int* widestln, int* maxtokens) {
currsz = 0;
tokens = 0;
}
readsmt = 0;
continue;
}
@ -47,7 +62,6 @@ void getinfo(FILE* input, int* lncount, int* widestln, int* maxtokens) {
ungetc(nc, input);
}
currsz++;
readsmt = 1;
}
rewind(input);

View File

@ -8,4 +8,5 @@ struct line {
};
void getinfo(FILE* input, int* lncount, int* widestln, int* maxtokens);
void freelns(struct line** lns, int lnscount);
struct line** parse(FILE* input, int lncount, int widestln, int maxtokens);