r/cprogramming • u/No_Entertainer_6928 • 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:
5
Upvotes
View all comments
Show parent comment
2
u/nerd5code Aug 30 '26
<sys/types.h>is UNIX/POSIX/XPG, but also supported on sone other platforms (incl. most DOS→OS/2, Win, NT and OS/400); don't rely on it unless you actually specify platforms. Not ISO C, in any event. I don't see why you need to include it at all, but maybe I'm missing something. (Also, jsyk traditionally the system-/kernel-specific<sys/*>files were included before anything else, and things could break otherwise.)void *to pass function pointers around. Also, I’m still seeing thefoo*spacing everywhere. Don’t.DGLs? Legally, if you spløøt aDGLonto a newly-malloc’d block, anything after would get messy without a flex array or jump pointer, so it looks like it could just be statically allocated, in which case it would be vastly less annoying to provide ctor and dtor, not allocator and deallocator. (And using dynamic alloc raises the question of where and how the thing is allocated, which might be irritating if the developer-user knows better than you. And sometimes you do implement ctors/dtors but call themnew/free, which is such a bad idea.)DFT_SCALAR,DFT_PARALLEL, andFFTas instances ofFourierAlgorithmis crazy work. Also, where is this used? Why is it public? Why must the developer-user avoid the identifierFFTqua global?DataPointsdoes not need to be allocated. Its referent might, but it also might not!; why can’t the developer-user work from a static const array, for example, or write to an auto array?mallocis a terrible idea for anything remotely NUMAlike. Anddouble complexis a really bad idea for ordering tokens (_Complex/complex doubleis more customary, and more likely to work with less-usualcomplexexpansions), and why are you not usingcomplex_t(which you shouldn’t use, but then why is it defined?)?fourier_transformshould have arestrictedtarget; if not, you need to deal with thetarget(should bedestordst, if the other issourceorsrc)== sourcecase. Also,boolshould almost never be used as a parameter;toshould be anintorunsignedwhose value is sourced from anenumtype.ZERO_INITis zero. Why… why?GRAD_EPSandEPSare beyond arbitrary, as isMAX_STEP. Also, rrrrrrrrrrrrrrrrrrrrrrrreally bad names to#definein a library header, andsizeofalone tells you precisely fuck-all aboutreal_t. You don’t know the bit-width (counterexample: TI ISAs wheresizeofeverything == 1 becauseCHAR_BIT == 32), you don’t know that all the bits of the size are actually occupied (counterexamples: most MCS-87/iAPX286/IA32long doubles and some x64long double, some M68Klong double/_Float64x), you don’t know the actual acceptable range for C math within the format (which you don’t know), etc. This is why you need the<float.h>constants to be bound toreal_t, and whyreal_tis fugging useless as-is.In a math library, “vector” does not mean “C++
std::vector,” it means a contiguous (or occasionally strided) block of values operated on all at once. Compare to GNUV4SFmode or__attribute__((__vector_size__(…))). And here again, you really shouldn’t set up an abstractly-typed vector, you want a different vector type for each element type, and the length should be stored separately so you can act on subranges of matrices.Oh god, what will the matrix type look like
NegContextcannot possibly be useful, and any application-exposed callback needs a leadingvoid *funarg.Vectorto be this complicated type, you’re doing all this stuff that has nothing to do with math. Let the user allocate memory and fill it.Vector_printbe useful?? You realize most actual formats have actual requirements in terms of formatting, that won’t be captured accurately by a single-parametered function? You realize thatstdoutis rarely the only important output stream?Vector_all_closeis wretched. The tolerance needs to be a parameter, and you need to generalize the underlying operations.Vector_max/-_minare the first two vector functions I see that should actually exist, but they should be extern inline. Sorting is absolutely not something you need to do.broadcast_addname, especially since you aren’t usingbroadcast_mulforscaleand lack abroadcast_div; it would make more sense to have separate broadcast and add ops, but ascalar_addwould make sense as a single function, operations+naming-wise.gradientfunctions, include funargs for the callbacks or your developer-users will be rendered miserable for no blasted reason. Also,//ing out blocks of code is a very Java thing to do.MatrixStatus, which exactly match C’s default assignment.FROBENIUSandSPECTRALare powerful bad identifiers to export from a library. Prefixes are your friends.#includeing after you’ve done other stuff? The only thing that should precede#includes is typically preprocessor directives (e.g., to detect which headers should be used), not declarations. And typically, you should expect the standard headers to have been included before yours, so it’s odd that you’re including"vector.h"before<stddef.h>.Matrix’s usage is wholly incompatible withVector’s. Nope. Nope nope nope. Matrices are bundles of vectors, and if you can’t represent that somehow with your data structures, you’re doing it wrong. Look at existing BLAS libs for ideas, setting aside their FORTRANness.Matrixes, you need to take a pointer (oftenrestrict) as the first parameter, and OOP it up. You’re being super-inconsistent about it, in any event, and returning a struct that requires special teardown is a marvelous way to accidentally leak memory, because the developer-user is in no sense obligated to do anything with the return value.Matrix_likeis awful naming, and I note that it andMatrix_copyoverlap entirely in purpose.Matrix_cloneis a stupid thing for your library to include, but at least the name doesn’t look like a social media operation.Matrix_QR,Matrix_Hessenberg,Matrix_QR_Hessenberg,Matrix_Hadamard_dot; unlessQR,Hessenberg, andHadamardare types or you’re aping MS/IBM naming (fuck no), don’t titlecase function names or characters following_. Lower-initial camelCase is fine also, and often better if you’re using_like::.Matrix_eigen[vals] would make more sense thanMatrix_eigvals. Abbreviating “eigen” is a bit like abbreviating “the.”[[deprecated]](C23, GCC 8, newer Clang: prefer__deprecated__in libraries to avoid collision with macros nameddeprecated), GNUish C (GCC 2.7ish, Clang, ICC/ECC/ICL in non-MS modes, newer TI, Sun/Oracle 12.4+, newer IBM, various embedded and others) supports__attribute__((__deprecated__)), and IIRC newer MS[V]C supports__declspec(deprecated)(which may be unusable ifdefined deprecated). Various libcs also define macros for this.config.cshould not exist. If you want a util.c, fine, but keep its gunk all as internal as possible. If you want to initialize the math library,config_initis a really, intensely bad name for it.detect_L3_cache_sizeis laughably nonportable. Like… it’s not even portable across Linux, just newer Linux that happens to have a sysfs mount at /sys and a CPU with an L3 cache. Again, this is works-for-me shit.Also, you know you can detect cache sizes directly?
if(!(f = fopen(…)))is generally better, because it puts the check and the operation in the same place, and ensures they don’t drift apart.size_tis wider thanunsigned long long, or that the value you get fits withinsize_t. No checks whatsoever.(cont’d)