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:

  1. outside the function
  2. on the heap

Linking libraries

Taking input

#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


References

  1. scanf
  2. fflush