Coding FAQ - goofycoder/knowdb GitHub Wiki
Q: stack vs heap allocation
Stack
- (+) faster (just move the stack pointer (esp))
- Use memory pools, you can get comparable performance out of heap allocation
- (-) stack's size is very limited
- lifetime of function frame
- usually stack-allocated memory is guaranteed in the cache (better cache locality)
Q: How do you compare structs for equality in C?
A: C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.
Reasons that memcmp() would not work:
-
The padding in the struct could be different.
-
Consider a "BOOL" field. In terms of equality, any non-zero BOOL is equal to every non-zero BOOL value. So while 1 and 2 may both be TRUE and therefore equal, memcmp will fail.
Reference: http://stackoverflow.com/questions/141720/how-do-you-compare-structs-for-equality-in-c
Q: Is it legal to do this:
char *str = "hello world\n";
char *p = (char*)malloc(strlen(str)+1);
strcpy(p, str, strlen(str)+1);
p = p+5; // advance the pointer
free(p);
A: Illegal. The output is likely to be:
*** glibc detected *** free(): invalid pointer: 0x0000000000XXXXXX ***
Abort
You are not allowed to free pointers not obtained from malloc()according to http://c-faq.com/malloc/crash.html