Quote:
Originally Posted by schmitta
Will the code on line marked 20 work in that the returned address will address the proper structure of the array symbtab and that the C compiler will know that I am talking about the struct symbol pointed to by i? (ie. (*i).name?) right now it is causing a out-of-bounds memory access (fault).
|
An advisable thing to do here is to create a new thread, for a couple of reasons.
- Exposure of the question portion related to C syntax to those who may contribute but not have much to offer because they think it's about GDB
- Highlight of a C syntax question for others searching for similar questions
I would personally not bother returning the pointer to a structure; just return the index since the array and size of it is global. I would make that strcmp() be a strncmp() and use the size of the strings contained in your structure.
One problem is that your structure is not allocated.
Code:
struct symbol {
unsigned char type;
char *name;
}symtab[TABLEN];
name is a pointer. You need to either allocate and initialize that structure or start by declaring those strings with fixed sizes; like:
The problem occurs when you're printing out the string "name" you are printing out the contents of an uninitialized pointer.
Another recommendation is to enable as much compiler warnings as you can. Here's a selection of warning flags which I typically use, because -Wall does not catch them all.
Code:
-Werror -Wall -Wextra -Wswitch-default -Wswitch-enum -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wmissing-noreturn
Don't ignore warnings, here's the output if you just compile with no extra flags:
Code:
~/testcode$ gcc -o table table.c
table.c: In function ‘main’:
table.c:19: warning: initialization from incompatible pointer type
table.c:20: warning: incompatible implicit declaration of built-in function ‘printf’
table.c:20: error: dereferencing pointer to incomplete type
Here's the output if you put in extra warning flags:
Code:
~/testcode$ gcc -Werror -Wall -Wextra -Wswitch-default -Wswitch-enum -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wmissing-noreturn -o table table.c
cc1: warnings being treated as errors
table.c:13: error: function declaration isn’t a prototype
table.c: In function ‘main’:
table.c:19: error: initialization from incompatible pointer type
table.c:20: error: implicit declaration of function ‘printf’
table.c:20: error: incompatible implicit declaration of built-in function ‘printf’
table.c:20: error: dereferencing pointer to incomplete type
table.c: In function ‘get_symbtab’:
table.c:42: error: implicit declaration of function ‘strcmp’