r/cprogramming • • Aug 30 '26

Math library code review

I am relatively new to C so I try to improve my skills by making a math library. The biggest challenge was making generic containers for matrices and vectors, as I was kind of new to void pointer magic. I think I have polished the most glaring issues in the code but do any of you have suggestions for what I could be doing better in my approach to C? Github for reference:

https://github.com/VatoQ/hoema-prak-clang

5 Upvotes

8 comments sorted by

View all comments

Show parent comment

2

u/nerd5code Aug 30 '26
  • strstr is the wrong function for the L3 mess; you’re looking at the end of the string, so find that, save the character, and switch on it.
  • I also note that nothing requires all threads to have the same L3 cache, or for the first thread’s cache sizes to imply anything about other threads’ caches.
  • elem_size is so bad. Soooooooo bad. First of all, case doesn’t make statements, it’s a label. {} does fuck-all in this case. Second, you’re placing the labels at the wrong indentation in most styles—as in assembly language, the label is typically placed at the base indentation for the scope, so case and switch should generally line up. This is especially important if the case happens to be in a subordinate statement. Third, the default case should be a for(;;) abort(); or error return; 1 is not generally reasonable. And this function shouldn’t need to be a function, and it shouldn’t need to exist!
  • So yeah, you’re doing #defines in public config.h (int_t real_t complex_t), which if redefined improperly (which you permit readily) will bring the headers into conflict with the compiled library. This is why you define separate APIs for separate types; if you have to, use private xheaders and private/temporary macros to spløøt each version, given a type parameter and limit macro prefix.
  • set_int_limit and set_real_limit are incorrect.

    1. You don’t understand how the C value and representation concepts differ. E.g., typically an int40_t will have the same size as an int64_t, just with several padding bytes. Size tells you nothing about range; you’d need the limit constants for that.
    2. You assume that the size will either match int, long, or long long; short, (nonstd.) short short, (nonstd.) short long, signed char, intXX_t, int_leastXX_t, int_fastXX_t, __int128/__int128_t, intptr_t, and ptrdiff_t aren’t handled; and you don’t really do anything to prevent unsigned types from being used—which may be perfectly reasonable—so you might be way off on those limits.
    3. If you don’t match the size exactly (for all that matters), *out won’t be set.
  • set_real_limit’s minimum is useless. You actually need the MIN value most of the time.
  • set_real_limit assumes INFINITY is a thing, without anything actually validating that IEEE 754 or something similar is in use. I think this bumps your minimum required language level to C11. Again, this is why you can’t just say “ISO C” and expect it to be meaningful, especially when it comes to math.
  • No break on default case in set_real_limit or set_complex_limit. Hypothetically optional, but a bad idea to omit, and in any case you’ve done so inconsistently.
  • set_complex_limit doesn't actually make sense; there is no (int-like) minimum or maximum (float-like minimum == 0), because min and max apply to 1-dimensional inputs, and complex numbers are ≥2D. There’s a maximum magnitude, there are corners of bounding rectangles, but there is no maximum complex value.
  • In no case do you need to do + 0.0 * I, and if the imaginary component is always zero for min and max, you’re just getting the real limit. Also, you don’t need to have called set_real_limit(…, Min) unless you’re in case Min (have I told you I hate your enum names?), and you only need set_real_limit(…, Max) in case Max. So you’re just wasting effort and storage. Put a real_t t right after the switch’s {, and get the limit in the specific case(s) that require it.
  • get_limit is just begging for an aliasing violation.
  • You desperately need to coalesce your error codes into a single enumeration. I get that it can be useful to break them up sometimes, but that should usually be at the library level.
  • Oh, DGL isn’t even a thing yet. Well… it shouldn’t be, not anything like this. And it looks like your DGL should union its function pointers, right? It’s a discriminated union? But then, DGL_new with void *function parameter would be a really bad idea. Function and object pointers should be treated as existing in their own universes. C will let you convert freely between void * and void (*)(…), but you’re not guaranteed to be able to round-trip per ISO 9899, and neither does it guarantee useful results from this conversion. You can safely convert between arbitrary function pointer types, unlike object pointers, but that’s it, and it has to be explicit for prototype functions. So a union is a moderately better option.
  • You’re just logging any old thing in any old format, huh.
  • In logging.c, I again see a replicated #ifdef-#define for something you’ve unconditionally defined elsewhere. If you expect it to be a parameter, offload it and don’t define it yourself; else, define it in one place, as privately as possible.
  • I shouldn’t see ECMA-48 escape codes without you having dredged up some sort of POSIX.1-compatible isatty call. You cannot determine whether any stream is a tty using only the C library, and you cannot assume every tty supports ECMA-48 unless you’ve already detected something UNIXlike (whose tty customs tend to derive from the DEC VT100 hardware lineage).
  • Yeah, LOG_VERBOSITY is all-caps why? and it’s not thread-safe, which nothing notes. Ditto LOG_MODE (shouldn’t exist) and LOG_FILE_PTR; these need to be atomicized somehow, either by wrapping in a mutex or by doing something fancy and atomic. Otherwise, you need to carefully document exactly when it is and isn’t safe to log or configure logging.
  • Log_prefix is the wrong way to go about it. Put your enums into an xmacro that binds the prefix, and then you can just index into a static const char *const[]. Ditto Log_color. (—Which is extern-linkage for some reason.)
  • localtime trashes and relies upon static state. This interacts with threading also, so logging from more than one thread concurrently is not safe.
  • You need to fflush regardless at the end of Log_log.
  • You need to check that fprintf and fflush actually succeed, and disable logging if they fail.
  • Verbosity checks repeated unnecessarily, and they’re unnecessarily complex.
  • Log_info_threshold exists why? And it multiplies without an overflow check; %zu requires C99 and excludes older MSVCRT; and why is it printfing, for fuck’s sake? Do you need to trash the primary output for the program every time the info threshold (whatever that’s used for) is set? If you want to do a size check like this, it’d be object_size && count >= LOG_INFO_THRESHOLD / object_size, but even then I don’t see the point of making this an extern-linkage function.
  • I do hope your library isn’t packaging main.c by default. It shouldn’t be in the src directory; it should be in a /test directory or similar.
  • I shouldn't see ../ in your header paths. If you want to use include as an include directory, use option -I or the CPATH (most Unix) or C_INCLUDE_PATH (GNU, Clang) variable to add it to the include path, and then "" and <> will both work. But your public and private includes should be separate, and your public includes need their own container directory so they’re not pissing up the public include namespace. Your code is not the only thing in the universe.
  • matrix.c:1,2: Oh fuck no. Nope. Nope nope nope nope. You absolutely do not define feature-test macros like this. It’s effectively necessary for them to be done up with option -D or -include, and defining it arbitrarily inside the library without even using <unistd.h> or checking for _POSIX_VERSION is just weird. Either require POSIX.1 or don’t.
  • Oh now we’re using OpenMP, which we have neither mentioned nor checked for!! <omp.h> only exists if _OPENMP-0 >= whatever its minimum value is, some YYYYMML jobby like __STDC_VERSION__ or _POSIX_VERSION. And it has to be specifically enabled for most compilers, so it’s not like you can just include it whenever.
  • INITIALIZER is a marvelously mis-descriptive name, and an incredibly poor idea syntactically. Fortunately, I see you’re not actually using it.
  • static PRNG_state prng means your PRNG is non-threadsafe, which is … a decision.
  • Learn C operator precedence; in no C compiler ever has == been a lower precedence than ||. You only need parentheses if there’s some common, historical, or actual ambiguity (e.g., & vs. |, || vs. |; or for things like !!(x = y) that shut the compiler up).
  • Functions that take pointers should actually check nullness when it matters. You’re not doing that at all, which means any null-pointer argument that can be evaluated will imediately make your entire program’s behavior undefined as soon as it’s legal for a derefc to occur. static functions can assert; otherwise, you need an if and some means of indicating the error à EINVAL.
  • Your _$foo_to_$bar functions are, I believe, UB in quite a few cases (look at the rules for converting between floats and ints—there are potential UB cases in both directions IINM), but you have no idea which ones because you don’t actually know what types are involved. Also, leading identifiers with _ is really not a good idea in general, especially after you’ve already included libc headers. It’s fine for macro parameters, it’s sometimes fine for struct fields or local variables, but otherwise it’s bad juju at best, undefined behavior at worst for things like _Foo.

(cont’d)

2

u/nerd5code Aug 30 '26
  • Why is _to_$foo_workers not const? void (*const name[LEN])($PARAMS) is the syntax. Also, you don’t even check that you’ve gotten a nonnull index from it when you execute through it. This is just so much extra indirection and abstraction for something that ought to be high-performance and direct. And then, you still require actual, separate functions in the backend, you’re just blocking the developer-user from accessing them, and making life much more difficult for the optimizer and CPU brpred in the process. Why?? Is there a reason for this? Is it just some obscene Python urge, where you really want to make sure everything runs at the same, lame speed as the interpreter? Because if so, definitely add more global state that’s locked exclusively at every API call.
  • Do you need three completely separate return MATRIX_SUCCESS statements in _prepare_datatype? Wouldn’t it be better, perhaps, to gather all the information about each data type into a single, static const struct $something[], so you don’t have to scatter things around throughout countless switches and arrays?
  • Why are you logging errors from _prepare_datatype? You should already know that the arguments are valid, and then assert about that (default: assert(!*"invalid 'dt' field in B parameter"); for(;;) abort();).
  • Oh and now there’s a completely separate _elem_size function in matrix.c that only acts on long, double, and complex double for some reason, which is thus incompatible with elem_size from config.c. Swell. What a good idea. Also, please stop with the overbraced switches. Seriously, you need to learn the syntax before you attempt useful libraries. This all reeks of discomfort/unfamiliarity with basic aspects of the language.
  • matrix.c:235–248: holy fuck what is this, just … any of it? Why is mibi_byte_size a double? You’ve already breezed past the C11 assumption and you require snprintf, so you can just use size_t with z modifier, right? And you’ve already checked that m * n won’t overflow, right? —Oh wait, no you haven’t, so you’re just throwing numbers around. And you shouldn’t be logging here anyway.
  • Ohhhhhh you’re using posix_memalign. So, you haven’t checked for POSIX.1 yet (you have to detect, then #include <unistd.h>, and then test _POSIX_VERSION-0 >= 200112L), C11 (which you’ve assumed) gives you aligned_alloc, but MSVC gives you _alloc_aligned and _free_aligned only, and older Unix only gives you things like memalign or mmap. And I don’t get why you’re aligning in the first place; here again, if the developer-user wants cache line alignment, they can actually detect the cache line (32 ain’t it, in all likelihood) and allocate their own damn structure using the facilities actually present on the target platform. Your math library does not need to allocate memory like this.
  • Did somebody tell you to use underscore-prefixing?? Slap them about the face several times, and ignore anything else they tell you.
  • OK, I’m not trawling through all your matrix code. It's generally bonkers, not into it, not going to perform well, no idea why you’re logging in the weirdest possible places.
  • Are you actually checking that the Matrix’s memory was allocated? …Kind of, only in one place. You log (inappropriately) and return an “empty” matrix, then insufficiently many things actually check for it. It’s an overcomplicated approach. And … I’m not checking the rest of this file. It’s a damned mess. Just everything thrown everywhere, bizarre decisions about macro usage, no fun.
  • So you’ll define arbitrary constants in public headers where they aren’t needed, but you won’t define the shift constants you repeat throughout prng.c, or 0x94D049BB133111EBULL. Uh huh. And why are you using size_t for the context, when the data types you’re working with need have nothing to do with its value range? If int_t ⇒ long long and you’re targeting ILP32, then you can’t generate the full range of int_t values from your PRNG. And then, if you’re working with doubles, you’ve got both an exponent and mantissa to reach, give or take transcendentals and subnormals.
  • Why are you repeating your XORshift-multiply blocks?
  • Why are you placing =s just anywhere? Either indent consistently or don’t. I suggest not, because it makes a mess.
  • You’re using const very inconsistently on locals. Either don’t or do, but splitting the difference doesn't inspire confidence. Also, in some cases you don’t need the variable at all; if you’re only using the value once and it’s obvious what it is, capturing it as x doesn't add anything, and in unoptimized builds it’ll do an extra memory hit; register would fix that and be more in line with intent. (Ignore people who tell you it does nothing. It does nothing in C++, prior to its removal from the language. It does something in C, it just isn’t required to have a noticeable effect.)
  • Your for(;;)s in your PRNG_State_* functions are bad ideas; nothing prevents them from looping indefinitely.
  • <alloca.h> is never something a library should rely on if you want it to be considered portable. Nothing about it is portable. The header isn’t, the function or “function” isn’t, its behavior and required placement isn’t, its interaction with inlining isn’t, etc. A paired malloc-free where the compiler can see both and knows both will be called is just fine; often it’ll be able to optimize to VLAs, if that’s appropriate.
  • Here again, PARALLEL_THRESHOLD is defined in multiple places, and its default value in vector.c is different than the other definition.
  • _parallel_condition is such a bad name. What is the function doing? What is the condition? Also, (size_t)(dim - lower) <= upper is how you do a range check, and you don’t need the variables that way. Not that you should be consulting non-const static state like this in the first place.
  • p == NULL is just !p in C, as is x == 0. Only for floats or enums would I explicitly use == 0.0 (rarely) or == ZERO_ENUM (if there’s no obvious Boolean correspondence for the enum values).
  • The potential for shape mismatch is something that should be hoisted so it’s more obvious to the developer, because this just shoves all the important stuff behind a mess of functions that then forward into a bigger mess of functions. Also it’d be a programmer error, not a warning.
  • #pragma omp anything needs to be paired with _OPENMP detection. There’s nothing actually constraining pragmas without it; ideally, the compiler does nothing with a pragma it doesn’t recognize, but #pragma omp is only constrained iff OpenMP is actually supported and active for the build, so it could do anything if not. It’s likely to raise warnings if not, in any event. Also #pragma omp simd requires like … OpenMP 3 or 4 I wanna say? Not sure offhand, but it needs to be detected. Also, most compilers can vectorize a short loop like this without your assistance, and the reason this sort of thing ought to be as inlined as possible is so that, when somebody’s repeating as vector operation across multiple rows/columns of a matrix, the compiler can potentially vectorize the entire thing together, which might enable it to skip lead-in/-out etc.
  • I still hate ACCESS_VOID, and I hate how much you’re leaning on it.
  • If you ever extend your data type enum, you’re so fucked.
  • Yyyyyyyyyyyyeah if you’re going to do a sort, you need to document the algorithm. But you shouldn’t, and you aren’t sorting as quickly as you could be, which is why you should leave it to the devel-user. (Also qsort is arguably better for in-place sorts, though its lack of funarg fucks its usefulness up quite a bit.)
  • Oh god you’re #pragma omp simding the macros that don’t need to exist. What made you decide that any of that was a good idea? An inlined for loop would be fine 99% of the time; you don’t/shouldn’t need SUB, and you certainly shouldn’t assume #pragma omp simd can be applied to it, because it should probably be in a do/while(0) in the first place. You can potentially embed _Pragma("omp simd") (C99 non-MS/ICL, GNU 3, Clang, ICC/ECC 8+, most C99-capable compilers) or __pragma(omp simd) (defined _MSC_VER || (defined __clang__ && defined __pragma) || defined __INTEL_COMPILER_BUILD_DATE) within the macro, but again, you shouldn’t need to.
  • Every single operation you perform on a signed integral type or floating-point type needs to be bounds-checked, because overflow is undefined behavior. Even _negate_int can overflow (at INT_MIN, for two’s-complement or asymmetric mappings to unsigned value) (which is still distinct from bytewise representation). If you rely on f.p. transcendentals, you need to detect them (__STDC_IEC_559__, __STDC_IEC_60559_*__, GNU __GCC_IEC_559, GNU __GCC_IEC_559_COMPLEX, GNU __FOO_IS_IEC_60559__), and you often have to check complex and real f.p. separately.

    Also, you do know that GNU dialect permits _Complex to be applied to things other than floating-point types? It’s UB or ISB in C99, but it’d be somewhat reasonable for somebody to #define complex_t _Complex long _Fract just to fuck with you.

OK, I'm not doing tests.

Sooooooo many of these functions you repeat for every blasted data type could just have been macros or xheaders, which would divide the amount of code you need by 3, and completely obviate the need for the _ts that oughtn’t be.

And the important aspects of the math stuff (e.g., dealing with corner cases) just aren’t here.