Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 17945

How should I dynamically allocate memory inside of a C function?

$
0
0

I'm just looking for a better way to dynamically allocate an "array" in C. I'm used to C++, Rust and Python where you can just use vectors or lists and would really appreciate some feedback.

I've written a lexer to tokenise a given input (e.g. a text file). Additionally I needed a function to automatically proceed to the next token and collect all the tokens in an array and came up with the following:

Token* Lexer_Run(Lexer* lexer, int* destination_size){    int i = 0, size = 128;    Token* destination = (Token*)malloc(size * sizeof(Token));    if (destination == NULL)        die("Memory allocation failed!");    Token token = Lexer_Advance(lexer);    while (token.type != TOKEN_EOF)    {        if (i >= size - 1)        {            size *= 2;            destination = (Token*)realloc(destination, size * sizeof(Token));            if (destination == NULL)                die("Memory allocation failed!");        }        destination[i] = token;        i++;        token = Lexer_Advance(lexer);    }    destination = (Token*)realloc(destination, i * sizeof(Token));    if (destination == NULL)        die("Memory allocation failed!");    *destination_size = i;    return destination;}

This works but perhaps there is a better way of accomplishing this? This looks too complex for such a simple task but maybe that's just C... Also I don't like the fact that I essentially have to abuse an argument to the function (destination_size) as a "return value".


Viewing all articles
Browse latest Browse all 17945

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>