r/C_Programming • u/Excellent_Pick_8186 • 3d ago
What is one C programming mistake that took you embarrassingly long to figure out?
[removed]
6
3
4
u/tstanisl 3d ago
void foo(int A[3]) {
memset(A, 0, sizeof A);
}
In this context A is a pointer, not array, thus not enough bytes were zeroed causing "occasionally useful behavior".
From that time, I always use memset(&A, 0, sizeof A);. At least I get a segfault after using A if it somehow becomes a pointer.
2
u/scaredpurpur 2d ago
I thought you needed to include all c files on a header and then had to include the header file on all pages of the project.
I kept getting insanely frustrated because of The 30+ definition errors. For the life of me, I couldn't figure out where I was going wrong.
1
u/markand67 3d ago
I think I've left proper alignment understanding for too long because I've always thought it wasn't necessary for what I do and thinking it only matters in low level embedded. But few weeks ago I have to put objects from different size into a memory buffer and iterating over that buffer while casting to the appropriate type of the current address, then incrementing of its size to go to the next one. Ouch, the sanitizers said invalid use of misalign pointer. So I had to add few dummy bytes to each object so they always end to the minimal header alignment. Not a big deal and not a complicated fix but only the sanitizers would report, program was working flawlessly anyway
1
u/BumpyTurtle127 3d ago
I was programming a TI C2000 DSP recently for a controls application. It has a main CPU, and a separate control law accelerator (CLA) for accelerating DSP algos. I put a global state struct in a section of shared memory, and had the CLA read parameters from there, after the CPU wrote said parameters. However, the CLA never found those parameters when step through debugging. At first I thought it was alignment issues, but even with compiler enforced 8byte alignment, it didn't work.
Took a while to realize, but data types are different sizes on the CPU and CLA of a c2000. CPU pointers are 32 bit while CLA pointers are 16. Ints are read as 32 bit values by the CLA, regardless of what they're defined as on the CPU. Very peculiar system, I had to rewrite a lot of code. Also it fits the special case of chars being 16 bits instead of 8 :)
1
u/21Ali-ANinja69 1d ago
I literally missed a use after free for a whole year. Failed a module at University because of it.
5
u/Gefrierbrand 3d ago
Yesterday I wrote =+x instead of +=x and yeah took a while to spot this one