I am trying to write an assembler for the RiSC CPU, Ridiculously simply computer - more information about this can be found here - Link to CPU information.
I have been programming in C for some time now and I am running into an issue. The first step of my assembler is to find all of the Labels and take note of their location, right now I am trying to create an array of simply the names of the labels, and a separate array containing the line of asm that they will point to.
I have the following function which parses a line of assembly code and finds the Labels:
int lcount=0;
int lineCount = 0;
char * BuildLabels(char * line, FILE *in, char *Labels[], char *LabelVals[])
{
char lineString = fgets(line,MAX_LENGTH,in);
if(lineString!=NULL)
{
char * FirstToken = strtok(line," \t\n");
if(FirstToken[0]!='#' || FirstToken != NULL)
{
if(FirstToken[strlen(FirstToken)-1]==':')
{
Labels[lcount] = FirstToken;
LabelVals[lcount] = lineCount;
printf("%s : %d\n",Labels[lcount],lcount);
lcount++;
}
lineCount++;
}
return Labels[lcount];
}else
{
return NULL;
}
}
The function is being called by this segment of code in the main
char *Labels[NUM_LABELS];
char *LabelVals[NUM_LABELS];
while(BuildLabels(lineString,input,Labels,LabelVals)!=NULL)
{
}
printf("%s:%s\n",Labels[0],Labels[1]);
printf("Exiting Now...\n");
When I run this program I get the following output
Opening input...
Opening output...
start::0
done::1
count::2
neg1::3
startAddr::4
startAddr::startAddr:
Exiting Now...
Process returned 0 (0x0) execution time : 0.009 s
Press any key to continue.
So..The arrays are changed in the function but they are not affected in the main? I expect the last line to be start::done: and not startAddr::startAddr.
I thought this was strange so I wrote the following function and it alters the strings in both the function being called and the main as expected when I try to print Labels[0] and Labels1
void Testing(char *Labels[])
{
lcount = 0;
Labels[lcount] = "Testing";
lcount++;
Labels[lcount] = "Double Testing";
}
When I call this function from the main and then try to print Labels[0] and Labels1 it prints out "Testing:Double Testing"
I'm not understanding why the previous function isn't working properly - also this is not homework, I want to learn more about compilers/assemblers as I'm used to working in Verilog/VHDL.
Any help is appreciated!
EDIT: This ended up being my solution, could someone possible explain to me why this works?
Labels[lcount] = malloc(strlen(FirstToken)+1);
strcpy(Labels[lcount],FirstToken);
lcountandlinecountglobally defined?