Do I cast the result of malloc?

In this question, someone suggested in a comment that I should not cast the result of malloc. i.e., I should do this: int *sieve = malloc(sizeof(*sieve) * length); rather than: int *sieve = (int *) malloc(sizeof(*sieve) * length); Why would this be the case? 2 29 TL;DR int *sieve = (int *) malloc(sizeof(int) * length); … Read more

Improve INSERT-per-second performance of SQLite

Optimizing SQLite is tricky. Bulk-insert performance of a C application can vary from 85 inserts per second to over 96,000 inserts per second! Background: We are using SQLite as part of a desktop application. We have large amounts of configuration data stored in XML files that are parsed and loaded into an SQLite database for … Read more

What is the “–>” operator in C/C++?

After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4. Here’s the code: #include <stdio.h> int main() { int x = 10; while (x –> 0) // x goes to 0 { printf(“%d “, x); … Read more

scanf() Leaves the Newline Character in the Buffer

I have the following program: [c]int main(int argc, char *argv[]) { int a, b; char c1, c2; printf("Enter something: "); scanf("%d",&a); // line 1 printf("Enter other something: "); scanf("%d", &b); // line 2 printf("Enter a char: "); scanf("%c",&c1); // line 3 printf("Enter another char: "); scanf("%c", &c2); // line 4 printf("Done"); // line 5 system("PAUSE"); … Read more

Why is “while ( !feof (file) )” always wrong

What is wrong with using feof() to control a read loop? For example: [c]#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(int argc, char **argv) { char *path = "stdin"; FILE *fp = argc &gt; 1 ? fopen(path=argv[1], "r") : stdin; if( fp == NULL ){ perror(path); return EXIT_FAILURE; } while( !feof(fp) ){ /* THIS IS WRONG */ /* Read … Read more

Undefined, unspecified and implementation-defined behavior

What is undefined behavior (UB) in C and C++? What about unspecified behavior and implementation-defined behavior? and What is the difference between them? Best Answer Undefined behavior is one of those aspects of the C and C++ language that can be surprising to programmers coming from other languages (other languages try to hide it better). Basically, it is possible to write … Read more

Do I cast the result of malloc?

TL;DR int *sieve = (int *) malloc(sizeof(int) * length); Has two problems in result of malloc. The cast and that you’re using the type instead of variable as argument for sizeof. Instead, do like this: int *sieve = malloc(sizeof *sieve * length); Long version No; you don’t cast the result, since: It is unnecessary, as void * is automatically … Read more