Switching from C ++ (with a lot of STL use) to C to build an interpreter
I am switching from C ++ to C because I am rebuilding my toy interpreter. I used vectors to dynamically allocate objects like tokens or instructions in my programs, stacks and basically strings with all their aspects. p>
Now, in C, I won't have it all anymore. I know that I will also have to use a lot of memory management.
- I am completely new to C, I only know high level data structures from STL, how can I start with strings and dynamic memory allocation?
source to share
In C, the landscape is much simpler. You only have malloc
, calloc
, realloc
and free
.
malloc
allocates a few bytes and returns them to you, returning NULL on failure.
calloc
is the same as malloc, but does the size multiplication for you. (You give it sizeof (mytype) and number and it gives the correct size). It also fills the memory block with zeros.
realloc
takes a pointer earlier malloc
'd and resizes the underlying memory block. If the block can be expanded, it is, and if it cannot, then a new block is allocated, and the contents of the old block are copied into the new block. It returns NULL on failure.
free
returns previously allocated memory malloc
, calloc
or realloc
.
source to share
As you might have guessed, there will be a lot more work if you are used to C ++ and want to switch to C.
For your vectors, the usual approach is to use a linked list if you need a dynamic structure like an array. While this is not the same as a vector - O (1) , accessing it via O (n) in a regular linked list - this usually "does the job". Alternatively: don't use a dynamic array. A lot of situations can pass with a fixed array and constant MAX_ARRAY. For v0.2 at least :-)
For strings, you probably end up with something like:
struct string {
char *buf;
size_t length;
}
With a lot of fields to account for the allocated buffer versus the actual buffer used, etc. Then add a whole bunch of routines to add to the string, free it, copy another string, etc.
Stacks can be implemented in terms of a linked list or an array.
Have you noticed the pattern? Computer Science 101. Lots of rethinking wheels. The advantage is that you can optimize the data structures for your program. The downside is that you have to write a whole bunch of code to get back to where you probably are. And you will need a lot more unit tests.
source to share
Strings are just char arrays terminated with 0 (also '\ 0') (pretty hard core), but you can do whatever you want with your own functions, or maybe your own structure - you can create your own string.
Functions for ansi strings that are available natively: http://cplusplus.com/reference/clibrary/cstring/
source to share