Sh3b0 / cplus

Compiler for an imperative toy programming language
MIT License
4 stars 2 forks source link

Memory checks for arrays #5

Open Sh3b0 opened 2 years ago

Sh3b0 commented 2 years ago

Example code

routine main() is
    var x : array[5] integer;
    x[-1] := -1;
    x[0] := 0;
    x[6] := 6;
    println x[-1];
    println x[0];
    println x[6];
    return;
end

Expected behavor

Runtime errors as we access invalid indexes (btw, C+ arrays are 1-indexed)

Actual behavior

Prints -1, 0, 6 Although seems cool, it shouldn't be like this.

TonyDecvA180XN commented 2 years ago

Array offest work on a very simple formula: cell = start + index * stride; where stride is a size of an array element. If the index of an element exceeds the desired range - segmentation fault happens. Unfortuantely, tracking segfaults is not a trivial task as it might seem, C++ does not have it either. (More like it is C+ programmer responsibility). Index range validation would require some exception mechanism or any other error recovery system, which is huge task. Btw, errors can tracked on CRT level, however we would have to introduce exceptions (and thus, classes in C+) or platform-dependent code for POSIX or Win32 substitution which is not pleasant.

Sh3b0 commented 2 years ago

Well, I was thinking of just inserting an internal conditional branch on each array access (e.g., in IRGenerator::visit(ast::Identifier *id)) to compare the runtime values of array size and index being accessed, and potenitially exit with smth like "Array index out of bounds".