I’m following an online course for C (link) and this is a piece of the code with a few of my prints in it:
void Database_create(struct Connection *conn, int max_rows, int max_data)
{
printf("Database_create with max_rows = %d, max_data = %d\n",max_rows,max_data);
int i = 0;
printf("Starting for-loop\n");
for(i = 0; i < max_rows; i++) {
printf("i");
struct Address addr = {.id = i, .set = 0};
printf("a");
conn->db->rows[i] = addr;
}
printf("Done!");
}
When i run this, the function above is called, and here’s the output:
toon@ToonAlfrinkPC ~/Projects/lcthw $ ./ex17 test.db c 200 513
Database_create with max_rows = 200, max_data = 513
Segmentation fault
Now, i’m sure i’ve made a mistake somewhere in the for-loop but that is irrelevant, i’m concerned about the “Starting for-loop” not being printed. This must mean the error is somewhere between those 2 print statements.
Did initializing i or calling printf cause the segmentation error? if not, did the whitespace? how could it possibly?
Note: i did not forget to compile.
EDIT:
To make matters more confusing, the Database_create function now seems to work fine without any adjustments.
Is it possible for different functions to be ran at the same time? This is how the program goes:
if(argc != 5) die(conn, "USAGE: ex17 <dbfile> create <max_rows> <max_data>");
Database_create(conn,atoi(argv[3]),atoi(argv[4]));
Database_write(conn);
break;
The Database_write function seems to cause the error, is it possible for that error to be thrown before Database_create is done?
EDIT:
i said ‘without any adjustments’, but i did put a newline after the last comment (“Done!\n”).
stdout is usually line buffered. So unless the string you print is newline terminated it will be buffered and displayed later, possibly as late as when the program exits.
What this means is that the problem might occur after a printf even if you don’t see its output.
To avoid that put a fflush(stdout) after all printf statements that don’t have a terminating
newline.