C interview questions
18 questions with answers. 950 open jobs in India ask for C.
Should I cast the result of malloc (in C)?
No; you shouldn’t cast the result, since:
- It is unnecessary, as
void *is automatically and safely promoted to any other pointer type in this case. - It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).
- It makes you repeat yourself, which is generally bad.
- It can hide an error if you forgot to include
<stdlib.h>. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. Note: as of C99 implicit functions are gone from C, and this point is no longer relevant since there's no automatic assumption that undeclared functions returnint.
As a clarification, note that I said “you shouldn’t cast”, not “you don't need to cast”. In my opinion, it's a blunder to include the cast, even if you got it right. There are simply no benefits to doing it, but a bunch of potential risks, and including the cast indicates that you don't know about the risks.
Also note, as commentators point out, that the above talks about straight C, not C++. I very firmly believe in C and C++ as separate languages.
To add further, your code needlessly repeats the type information (
int) which can cause errors. It's better to de-reference the pointer being used to store the return value, to "lock" the two together:int *sieve = malloc(length * sizeof *sieve);Some may say: “Well, previously the type was repeated, and now the variable name is repeated; isn’t this just as repetitive as before? How is that any better?” The difference is that if you one day change the type of the variable and forget to change the type under the
sizeofto match, you will silently get an allocation of the wrong size and no warning about it; but if you change the name of the variable, but forget to change the name undersizeofto match, it is more probable that the old name no longer resolves to anything, so your code will stop compiling, prompting you to fix the mistake.This also moves the
lengthto the front for increased visibility, and drops the redundant parentheses withsizeof; they are only needed when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember:sizeofis not a function! :)While moving
lengthto the front may increase visibility in some rare cases, one should also pay attention that in the general case, it should be better to write the expression as:int *sieve = malloc(sizeof *sieve * length);Since keeping the
sizeoffirst, in this case, ensures multiplication is done with at leastsize_tmath.Compare:
malloc(sizeof *sieve * length * width)vs.malloc(length * width * sizeof *sieve)the second may overflow thelength * widthwhenwidthandlengthare smaller types thansize_t.From Stack Overflow: asked by Patrick McDonald, answered by unwind (CC BY-SA 4.0)
- It is unnecessary, as
What does the ??!??! operator do in C?
??!is a trigraph that translates to|. So it says:!ErrorHasOccured() || HandleError();which, due to short circuiting, is equivalent to:
if (ErrorHasOccured()) HandleError();Guru of the Week (deals with C++ but relevant here), where I picked this up.
Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.
From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):
The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.
From Stack Overflow: asked by Peter Olson, answered by user786653 (CC BY-SA 4.0)
What is ':-!!' in C?
This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.
The macro is somewhat misnamed; it should be something more like
BUILD_BUG_OR_ZERO, rather than...ON_ZERO. (There have been occasional discussions about whether this is a confusing name.)You should read the expression like this:
sizeof(struct { int: -!!(e); }))(e): Compute expressione.!!(e): Logically negate twice:0ife == 0; otherwise1.-!!(e): Numerically negate the expression from step 2:0if it was0; otherwise-1.struct{int: -!!(0);} --> struct{int: 0;}: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.struct{int: -!!(1);} --> struct{int: -1;}: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.
So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take
sizeofthat field, so we get asize_twith the appropriate width (which will be zero in the case whereeis zero).Some people have asked: Why not just use an
assert?keithmo's answer here has a good response:
These macros implement a compile-time test, while assert() is a run-time test.
Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.
From Stack Overflow: asked by chmurli, answered by John Feminella (CC BY-SA 3.0)
How do function pointers in C work?
Function pointers in C
Let's start with a basic function which we will be pointing to:
int addInt(int n, int m) { return n+m; }First thing, let's define a pointer to a function which receives 2
ints and returns anint:int (*functionPtr)(int,int);Now we can safely point to our function:
functionPtr = &addInt;Now that we have a pointer to the function, let's use it:
int sum = (*functionPtr)(2, 3); // sum == 5Passing the pointer to another function is basically the same:
int add2to3(int (*functionPtr)(int, int)) { return (*functionPtr)(2, 3); }We can use function pointers in return values as well (try to keep up, it gets messy):
// this is a function called functionFactory which receives parameter n // and returns a pointer to another function which receives two ints // and it returns another int int (*functionFactory(int n))(int, int) { printf("Got parameter %d", n); int (*functionPtr)(int,int) = &addInt; return functionPtr; }But it's much nicer to use a
typedef:typedef int (*myFuncDef)(int, int); // note that the typedef name is indeed myFuncDef myFuncDef functionFactory(int n) { printf("Got parameter %d", n); myFuncDef functionPtr = &addInt; return functionPtr; }From Stack Overflow: asked by Yuval Adam, answered by Yuval Adam (CC BY-SA 3.0)
What does "static" mean in C?
Usually, you will see the
statickeyword in these places:- A static variable inside a function keeps its value between invocations.
- A static global variable or function is "seen" only in the file in which it's declared.
(1) is the more foreign topic if you're a newbie, so here's an example:
#include <stdio.h> void foo() { int a = 10; static int sa = 10; a += 5; sa += 5; printf("a = %d, sa = %d\n", a, sa); } int main() { int i; for (i = 0; i < 10; ++i) foo(); }This prints:
a = 15, sa = 15 a = 15, sa = 20 a = 15, sa = 25 a = 15, sa = 30 a = 15, sa = 35 a = 15, sa = 40 a = 15, sa = 45 a = 15, sa = 50 a = 15, sa = 55 a = 15, sa = 60This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.
(2) is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made
static, so that the user won't be able to access them. This is encapsulation, a good practice.Quoting Wikipedia:
In the C programming language,
staticis used with global variables and functions to set their scope to the containing file. In local variables,staticis used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.See here and here for more details.
And to answer your second question, it's not like in C#.
In C++, however,
staticis also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.Additionally, in C,
staticcan be used in array declarators to specify minimum size of the array (non-function array declarators cannot use this keyword). Consider this declaration:void func(int foo[static 42]);The function
func()takes an array of at least 42 elements.Note that C++ does not support this use of the
statickeyword.From Stack Overflow: asked by David, answered by Eli Bendersky (CC BY-SA 4.0)
What is the difference between ++i and i++?
++iwill increment the value ofi, and then return the incremented value.i = 1; j = ++i; (i is 2, j is 2)i++will increment the value ofi, but return the original value thatiheld before being incremented.i = 1; j = i++; (i is 2, j is 1)
For a
forloop, either works.++iseems more common, perhaps because that is what is used in K&R.In any case, follow the guideline "prefer
++ioveri++" and you won't go wrong.There's a couple of comments regarding the efficiency of
++iandi++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C?
As On Freund's comment notes, it's different for a C++ object, since
operator++()is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.From Stack Overflow: asked by The.Anti.9, answered by Mark Harrison (CC BY-SA 4.0)
Why does the C preprocessor interpret the word "linux" as the constant "1"?
In the Old Days (pre-ANSI), predefining symbols such as
unixandvaxwas a way to allow code to detect at compile time what system it was being compiled for. There was no official language standard back then (beyond the reference material at the back of the first edition of K&R, 1978), and C code of any complexity was typically a complex maze of#ifdefs to allow for differences between systems. These macro definitions were generally set by the compiler itself, not defined in a library header file. Since there were no real rules about which identifiers could be used by the implementation and which were reserved for programmers, compiler writers felt free to use simple names likeunixand assumed that programmers would simply avoid using those names for their own purposes.The 1989 ANSI C standard introduced rules restricting what symbols an implementation could legally predefine. A macro predefined by the compiler could only have a name starting with two underscores, or with an underscore followed by an uppercase letter, leaving programmers free to use identifiers not matching that pattern and not used in the standard library.
As a result, any compiler that predefines
unixorlinuxis non-conforming, since it will fail to compile perfectly legal code that uses something likeint linux = 5;.As it happens, gcc is non-conforming by default -- but it can be made to conform (reasonably well) with the right command-line options:
gcc -std=c90 -pedantic ... # or -std=c89 or -ansi gcc -std=c99 -pedantic gcc -std=c11 -pedanticBy the time you read this, gcc will support newer editions of the C standard. See the gcc manual for more details.
gcc might phase out these definitions (
unix,linux, et al) in future releases, so you shouldn't write code that depends on them. If your program needs to know whether it's being compiled for a Linux target or not it can check whether__linux__is defined (assuming you're using gcc or a compiler that's compatible with it). See the GNU C preprocessor manual for more information.A largely irrelevant aside: the "Best One Liner" winner of the 1987 International Obfuscated C Code Contest, by David Korn (yes, the author of the Korn Shell) took advantage of the predefined
unixmacro:main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}It prints
"unix", but for reasons that have absolutely nothing to do with the spelling of the macro name.I don't want to post any spoilers here, and I encourage anyone reading this to try to understand that code on their own first. But if you really want to give up, I've posted an explanation here: https://gist.github.com/Keith-S-Thompson/6920347
From Stack Overflow: asked by ahmedaly50, answered by Keith Thompson (CC BY-SA 4.0)
What is the difference between a definition and a declaration?
A declaration introduces an identifier and describes its type, be it a type, object, or function. A declaration is what the compiler needs to accept references to that identifier. These are declarations:
extern int bar; extern int g(int, int); double f(int, double); // extern can be omitted for function declarations class foo; // no extern allowed for type declarationsA definition actually instantiates/implements this identifier. It's what the linker needs in order to link references to those entities. These are definitions corresponding to the above declarations:
int bar; int g(int lhs, int rhs) {return lhs*rhs;} double f(int i, double d) {return i+d;} class foo {};A definition can be used in the place of a declaration.
An identifier can be declared as often as you want. Thus, the following is legal in C and C++:
double f(int, double); double f(int, double); extern double f(int, double); // the same as the two above extern double f(int, double);However, it must be defined exactly once. If you forget to define something that's been declared and referenced somewhere, then the linker doesn't know what to link references to and complains about a missing symbols. If you define something more than once, then the linker doesn't know which of the definitions to link references to and complains about duplicated symbols.
Since the debate what is a class declaration vs. a class definition in C++ keeps coming up (in answers and comments to other questions) , I'll paste a quote from the C++ standard here.
At 3.1/2, C++03 says:A declaration is a definition unless it [...] is a class name declaration [...].
3.1/3 then gives a few examples. Amongst them:
[Example: [...] struct S { int a; int b; }; // defines S, S::a, and S::b [...] struct S; // declares S —end exampleTo sum it up: The C++ standard considers
struct x;to be a declaration andstruct x {};a definition. (In other words, "forward declaration" a misnomer, since there are no other forms of class declarations in C++.)Thanks to litb (Johannes Schaub) who dug out the actual chapter and verse in one of his answers.
From Stack Overflow: asked by Maciek, answered by sbi (CC BY-SA 3.0)
What is the strict aliasing rule?
A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network message) onto a buffer of the word size of your system (like a pointer to
uint32_ts oruint16_ts). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:
#include <stdint.h> #include <stdlib.h> #include <stdio.h> typedef struct Msg { uint32_t a; uint32_t b; } Msg; // Sends a buffer over a 16-bit channel void SendWords(uint16_t *buf, size_t sz) { for(size_t i = 0; i < sz; ++i) printf("%.4x ", buf[i]); printf("\n"); } int main(void) { Msg msg; // Send a bunch of messages for(int i = 0; i < 10; ++i) { msg.a = 0xDEADBEEF; msg.b = i; SendWords((uint16_t*)&msg, sizeof(msg)/sizeof(uint16_t)); } }The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a compatible type or one of the other types allowed by C 2011 6.5 paragraph 71 is undefined behavior. Unfortunately, you can still code this way, maybe get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code. For example, when I compiled it with
gcc -O2it produced this very unexpected output:0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 ...See this snippet on Compiler Explorer for how GCC and Clang both produce different unintended outputs.
To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Following this rule, the writes to
msgcannot alias the reads ofbufinSendWords. Consequently, an optimizing compiler can reorder the instructions, so that all assignments tomsghappen before or after all the reads frombufinSendWords. In turn, it can then deduce thatbuf[0], ..., buf[3]can be loaded from memory before the loop is executed, or that only themsgvalues from the last iteration of the loop need to be calculated. Either way, removing the redundant stores and loads (under this rule) makes the generated code faster. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents ofbufcould change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.So how do I get around this?
Read the rest at the sourceFrom Stack Overflow: asked by Benoit, answered by Doug T. (CC BY-SA 4.0)
Obfuscated C Code Contest 2006. Please explain sykes2.c
Let's de-obfuscate it.
Indenting:
main(_) { _^448 && main(-~_); putchar(--_%64 ? 32 | -~7[__TIME__-_/8%8][">'txiZ^(~z?"-48] >> ";;;====~$::199"[_*2&8|_/64]/(_&2?1:8)%8&1 : 10); }Introducing variables to untangle this mess:
main(int i) { if(i^448) main(-~i); if(--i % 64) { char a = -~7[__TIME__-i/8%8][">'txiZ^(~z?"-48]; char b = a >> ";;;====~$::199"[i*2&8|i/64]/(i&2?1:8)%8; putchar(32 | (b & 1)); } else { putchar(10); // newline } }Note that
-~i == i+1because of twos-complement. Therefore, we havemain(int i) { if(i != 448) main(i+1); i--; if(i % 64 == 0) { putchar('\n'); } else { char a = -~7[__TIME__-i/8%8][">'txiZ^(~z?"-48]; char b = a >> ";;;====~$::199"[i*2&8|i/64]/(i&2?1:8)%8; putchar(32 | (b & 1)); } }Now, note that
a[b]is the same asb[a], and apply the-~ == 1+change again:main(int i) { if(i != 448) main(i+1); i--; if(i % 64 == 0) { putchar('\n'); } else { char a = (">'txiZ^(~z?"-48)[(__TIME__-i/8%8)[7]] + 1; char b = a >> ";;;====~$::199"[(i*2&8)|i/64]/(i&2?1:8)%8; putchar(32 | (b & 1)); } }Converting the recursion to a loop and sneaking in a bit more simplification:
// please don't pass any command-line arguments main() { int i; for(i=447; i>=0; i--) { if(i % 64 == 0) { putchar('\n'); } else { char t = __TIME__[7 - i/8%8]; char a = ">'txiZ^(~z?"[t - 48] + 1; int shift = ";;;====~$::199"[(i*2&8) | (i/64)]; if((i & 2) == 0) shift /= 8; shift = shift % 8; char b = a >> shift; putchar(32 | (b & 1)); } } }This outputs one character per iteration. Every 64th character, it outputs a newline. Otherwise, it uses a pair of data tables to figure out what to output, and puts either character 32 (a space) or character 33 (a
!). The first table (">'txiZ^(~z?") is a set of 10 bitmaps describing the appearance of each character, and the second table (";;;====~$::199") selects the appropriate bit to display from the bitmap.The second table
Let's start by examining the second table,
int shift = ";;;====~$::199"[(i*2&8) | (i/64)];.i/64is the line number (6 to 0) andi*2&8is 8 iffiis 4, 5, 6 or 7 mod 8.if((i & 2) == 0) shift /= 8; shift = shift % 8selects either the high octal digit (fori%8= 0,1,4,5) or the low octal digit (fori%8= 2,3,6,7) of the table value. The shift table ends up looking like this:row col val 6 6-7 0 6 4-5 0 6 2-3 5 6 0-1 7 5 6-7 1 5 4-5 7 5 2-3 5 5 0-1 7 4 6-7 1 4 4-5 7 4 2-3 5 4 0-1 7 3 6-7 1 3 4-5 6 3 2-3 5 3 0-1 7 2 6-7 2 2 4-5 7 2 2-3 3 2 0-1 7 1 6-7 2 1 4-5 7 1 2-3 3 1 0-1 7 0 6-7 4 0 4-5 4 0 2-3 3 0 0-1 7or in tabular form
00005577 11775577 11775577 11665577 22773377 22773377 44443377Note that the author used the null terminator for the first two table entries (sneaky!).
This is designed after a seven-segment display, with
7s as blanks. So, the entries in the first table must define the segments that get lit up.The first table
Read the rest at the sourceFrom Stack Overflow: asked by corny, answered by nneonneo (CC BY-SA 3.0)
Difference between malloc and calloc?
calloc()gives you a zero-initialized buffer, whilemalloc()leaves the memory uninitialized.For large allocations, most
callocimplementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIXmmap(MAP_ANONYMOUS)or WindowsVirtualAlloc) so it doesn't need to write them in user-space. This is how normalmallocgets more pages from the OS as well;callocjust takes advantage of the OS's guarantee.This means
callocmemory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.) The effects are visible with performance experiments on Linux, for example.Some compilers even can optimize malloc + memset(0) into calloc for you, but it's best to just use calloc in the source if you want zeroed memory. (Or if you were trying to pre-fault it to avoid page faults later, that optimization will defeat your attempt.)
If you aren't going to ever read memory before writing it, use
mallocso it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).Embedded implementations of
callocmay leave it up tocallocitself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.On embedded Linux, malloc could
mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS), which is only enabled for some embedded kernels because it's insecure on a multi-user system.From Stack Overflow: asked by user105033, answered by Fred Larson (CC BY-SA 4.0)
Why use apparently meaningless do-while and if-else statements in macros?
The
do ... whileandif ... elseare there to make it so that a semicolon after your macro always means the same thing. Let's say you had something like your second macro.#define BAR(X) f(x); g(x)Now if you were to use
BAR(X);in anif ... elsestatement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.if (corge) BAR(corge); else gralt();The above code would expand into
if (corge) f(corge); g(corge); else gralt();which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.
if (corge) {f(corge); g(corge);}; else gralt();There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.
#define BAR(X) f(X), g(X)The above version of bar
BARexpands the above code into what follows, which is syntactically correct.if (corge) f(corge), g(corge); else gralt();This doesn't work if instead of
f(X)you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something likedo ... whileto cause the macro to be a single statement that takes a semicolon without confusion.#define BAR(X) do { \ int i = f(X); \ if (i > 4) g(i); \ } while (0)You don't have to use
do ... while, you could cook up something withif ... elseas well, although whenif ... elseexpands inside of anif ... elseit leads to a "dangling else", which could make an existing dangling else problem even harder to find, as in the following code.if (corge) if (1) { f(corge); g(corge); } else; else gralt();The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare
BARas an actual function, not a macro.In summary, the
do ... whileis there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.From Stack Overflow: asked by jfm3, answered by jfm3 (CC BY-SA 4.0)
Why are these constructs using pre and post-increment undefined behavior?
C has the concept of undefined behavior, i.e. some language constructs are syntactically valid but you can't predict the behavior when the code is run.
As far as I know, the standard doesn't explicitly say why the concept of undefined behavior exists. In my mind, it's simply because the language designers wanted there to be some leeway in the semantics, instead of i.e. requiring that all implementations handle integer overflow in the exact same way, which would very likely impose serious performance costs, they just left the behavior undefined so that if you write code that causes integer overflow, anything can happen.
So, with that in mind, why are these "issues"? The language clearly says that certain things lead to undefined behavior. There is no problem, there is no "should" involved. If the undefined behavior changes when one of the involved variables is declared
volatile, that doesn't prove or change anything. It is undefined; you cannot reason about the behavior.Your most interesting-looking example, the one with
u = (u++);is a text-book example of undefined behavior (see Wikipedia's entry on sequence points).
From Stack Overflow: asked by PiX, answered by unwind (CC BY-SA 3.0)
What is a segmentation fault?
A segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs.
Whenever you get a segmentation fault, you know you are doing something wrong with memory – accessing a variable that has already been freed, writing to a read-only portion of the memory, etc. A segmentation fault is essentially the same in most languages that let you mess with memory management, and there isn’t any principal difference between segmentation faults in C and C++.
There are many ways to get a segmentation fault, at least in the lower-level languages such as C and C++. A common way to get a segmentation fault is to dereference a null pointer:
int *p = NULL; *p = 1;Another segmentation fault happens when you try to write to a portion of memory that was marked as read-only:
char *str = "Foo"; // The compiler marks the constant string as read-only *str = 'b'; // Which means this is illegal and results in a segfaultA dangling pointer points to a thing that does not exist anymore, like here:
char *p = NULL; { char c; p = &c; } // Now p is danglingThe pointer
pdangles, because it points to the character variablecthat ceased to exist after the block ended. And when you try to dereference a dangling pointer (like*p='A'), you would probably get a segmentation fault.From Stack Overflow: asked by Rajendra Uppal, answered by zoul (CC BY-SA 4.0)
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs:
- Mis-aligned access might be a hard error (often
SIGBUS). - Mis-aligned access might be a soft error.
- Either corrected in hardware, for a modest performance-degradation.
- Or corrected by emulation in software, for a severe performance-degradation.
- In addition, atomicity and other concurrency-guarantees might be broken, leading to subtle errors.
Here's an example using typical settings for an x86 processor (all used 32 and 64 bit modes):
struct X { short s; /* 2 bytes */ /* 2 padding bytes */ int i; /* 4 bytes */ char c; /* 1 byte */ /* 3 padding bytes */ }; struct Y { int i; /* 4 bytes */ char c; /* 1 byte */ /* 1 padding byte */ short s; /* 2 bytes */ }; struct Z { int i; /* 4 bytes */ short s; /* 2 bytes */ char c; /* 1 byte */ /* 1 padding byte */ }; const int sizeX = sizeof(struct X); /* = 12 */ const int sizeY = sizeof(struct Y); /* = 8 */ const int sizeZ = sizeof(struct Z); /* = 8 */One can minimize the size of structures by sorting members by alignment (sorting by size suffices for that in basic types) (like structure
Zin the example above).IMPORTANT NOTE: Both the C and C++ standards state that structure alignment is implementation-defined. Therefore each compiler may choose to align data differently, resulting in different and incompatible data layouts. For this reason, when dealing with libraries that will be used by different compilers, it is important to understand how the compilers align data. Some compilers have command-line settings and/or special
#pragmastatements to change the structure alignment settings.From Stack Overflow: asked by Kevin, answered by Kevin (CC BY-SA 3.0)
- Mis-aligned access might be a hard error (often
Improve INSERT-per-second performance of SQLite
Several tips:
- Put inserts/updates in a transaction.
- For older versions of SQLite - Consider a less paranoid journal mode (
pragma journal_mode). There isNORMAL, and then there isOFF, which can significantly increase insert speed if you're not too worried about the database possibly getting corrupted if the OS crashes. If your application crashes the data should be fine. Note that in newer versions, theOFF/MEMORYsettings are not safe for application level crashes. - Playing with page sizes makes a difference as well (
PRAGMA page_size). Having larger page sizes can make reads and writes go a bit faster as larger pages are held in memory. Note that more memory will be used for your database. - If you have indices, consider calling
CREATE INDEXafter doing all your inserts. This is significantly faster than creating the index and then doing your inserts. - You have to be quite careful if you have concurrent access to SQLite, as the whole database is locked when writes are done, and although multiple readers are possible, writes will be locked out. This has been improved somewhat with the addition of a WAL in newer SQLite versions.
- Take advantage of saving space...smaller databases go faster. For instance, if you have key value pairs, try making the key an
INTEGER PRIMARY KEYif possible, which will replace the implied unique row number column in the table. - If you are using multiple threads, you can try using the shared page cache, which will allow loaded pages to be shared between threads, which can avoid expensive I/O calls.
- Don't use
!feof(file)!
From Stack Overflow: asked by Mike Willekes, answered by Snazzer (CC BY-SA 4.0)
With arrays, why is it the case that a[5] == 5[a]?
The C standard defines the
[]operator as follows:a[b] == *(a + b)Therefore
a[5]will evaluate to:*(a + 5)and
5[a]will evaluate to:*(5 + a)ais a pointer to the first element of the array.a[5]is the value that's 5 elements further froma, which is the same as*(a + 5), and from elementary school math we know those are equal (addition is commutative).From Stack Overflow: asked by Dinah, answered by Mehrdad Afshari (CC BY-SA 3.0)
Compiling an application for use in highly radioactive environments
Working for about 4-5 years with software/firmware development and environment testing of miniaturized satellites*, I would like to share my experience here.
*(miniaturized satellites are a lot more prone to single event upsets than bigger satellites due to its relatively small, limited sizes for its electronic components)
To be very concise and direct: there is no mechanism to recover from detectable, erroneous situation by the software/firmware itself without, at least, one copy of minimum working version of the software/firmware somewhere for recovery purpose - and with the hardware supporting the recovery (functional).
Now, this situation is normally handled both in the hardware and software level. Here, as you request, I will share what we can do in the software level.
Read the rest at the sourceFrom Stack Overflow: asked by rook, answered by Ian (CC BY-SA 3.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA18 questions