C Programs (Misc.)
202308201250
Status: #idea
Tags: OS
C Programs (Misc.)
Memory Protection
int x;
scanf("%d", &x); // Takes an address
printf("%d", x); // Takes a value
scanf("%d", x); // Seg fault: Probably an address outside the program's block
int A[10];
// Something... int x;
printf("%d", A[11]); // Seg fault: If A is last address in block
// Could print garbage value, at address of x
int x;
printf("%d", 5); // May not be visible. Need to flush buffers to guarantee display
fflush(stdout); // Flushes stdout
scanf("%d", x); // Segfault
Info
To return more than one value, use pass by reference
Ensure you declare the reference:
- outside the function
- on the heap
Linking libraries
- Header files only the interface to interact with the library, i.e. the function declarations
- Implementation of the header files are stored in static library
.afiles, or dynamic.soshared object files.- Advantage of
.sofiles is that you don't need to recompile your main code, if there is a change in the shared object file, as long as it is linked to the new shared object file
- Advantage of
Taking input
- Generally, programs take multi-character input.
- The keyboard however, is an ASCII single-character input device
- The OS handles taking multiple characters of inputs, and converting it to an integer and providing it to the program running below
#include <stdio.h>
int x;
scanf("%d", x);
Info
scanf returns number of input items successfully matched and assigned
Warning
Delimiter for int input is any non-digit character
Info
realloc is used to expand current memory allocation