Exam Cards Flashcards
/bin
/bin is a standard subdirectory of the root directory in Unix-like operating systems that contains the executable (i.e., ready to run) programs that must be available in order to attain minimal functionality for the purposes of booting (i.e., starting) and repairing a system. In addition to /bin, some of the other standard subdirectories in the root directory include /boot, /dev, /etc, /home, /mnt, /usr, /proc and /var. Among the contents of /bin are the shells (e.g., bash and csh), ls, grep, tar, kill, echo, ps, cp, mv, rm, cat, gzip, ping, su and the vi text editor. These programs can be used by both the root user (i.e., the administrative user) and ordinary users. /bin is by default in PATH, which is the list of directories that the system searches for the corresponding program when a command is issued. This means that any executable file (i.e., runnable program) in /bin can be run just by entering the file name at the command line and then pressing the ENTER key. The contents of PATH can be seen by using the echo command as follows: echo $PATH
root
The root directory, which is designated by a forward slash ( / ), is the top-level directory in the hierarchy of directories (also referred to as the directory tree) on Unix-like operating systems. That is, it is the directory that contains all other directories and their subdirectories as well as all files on the system.
What is a file?
A file is a named collection of related information that appears to the user as a single, contiguous block of data and that is retained in storage (e.g., a hard disk drive or a floppy disk).
What is a directory in Unix?
A directory in a Unix-like operating system is merely a special type of file that contains a list of the names of objects (i.e., files, links and directories) that appear to the user to be in it along with the corresponding inodes for each object.
Inode
An inode is a data structure on a filesystem that stores all the information about a filesystem object except its name and its actual data. A data structure is a way of storing data so that it can be used efficiently.
Filesystem
A filesystem is the hierarchy of directories that is used to organize files on a computer system.
/sbin
contains additional programs to /bin that are used to boot the system as well as administrative and system maintenance programs that are only available to the root user.
/usr/bin
contains executable programs that are not required for booting or repairing the system.
/etc
Supervisor directory commands, configuration files, disk configuration files, valid user lists, groups, ethernet, hosts, where to send critical messages. This is the nerve center of your system, it contains all system related configuration files in here or in its sub-directories. A “configuration file” is defined as a local file used to control the operation of a program; it must be static and cannot be an executable binary. Examples: /etc/hosts.[allow, deny]: you can control access to your network by using these files. Adds hosts that you want to grant access to your network to the hosts.allow file; add hosts that you want to deny access to hosts.deny. /etc/ftpusers: this file contains the login names of users who are not allowed to log in by way of FTP. For security reasons, it is recommended to add the root user to this file. /etc/inittab: this file describes what takes place or which processes are started at bootup or at different runlevels. A runlevel is defined as the state in which the Linux box currently is in. Linux has seven runlevels, from 0-6. /etc/passwd: this file contains user information. Whenever a new user is added, an entry is added to this file containing the user’s login name, password and so on. This file is readable by everyone on the system. If the password field contains “x”, then encrypted passwords are stored in /etc/shadow, a file that is accessible only by the root user. /etc/profile: when a user logs in, a number of configuration files are executed, including /etc/profile. This file contains settings and global startup information for the bash shell. /etc/shells: this file contains the names of all the shells installed on the system, along with their full path names.
/usr/include
This is where all of the system’s general-use include files for the C programming language should be placed. The directory for ‘header files’, needed for compiling user space source code.
/usr/lib
The /usr/lib directory contains more libraries and data files used by various UNIX commands. UNIX program libraries
/var/log
Log files from the system and various programs/services, especially login (/var/log/wtmp, which logs all logins and logouts into the system) and syslog (/var/log/messages, where all kernel and system program message are usually stored). Files in /var/log can often grow indefinitely, and may require cleaning at regular intervals. Something that is now normally managed via log rotation utilities such as ‘logrotate’. This utility also allows for the automatic rotation compression, removal and mailing of log files. Logrotate can be set to handle a log file daily, weekly, monthly or when the log file gets to a certain size. Normally, logrotate runs as a daily cron job. This is a good place to start troubleshooting general technical problems
/var
Variable sized files - can grow and shrink dynamically, such a users mail spool and print spool files.
/
the root directory
.
current directory
..
parent directory
~
home directory (tilde)
ls
The ls command is used to list the contents of a directory. It is probably the most commonly used Linux command.
ls -l
List information about the FILEs (the current directory by default) in long format.
ls -la ..
List all files (even ones with names beginning with a period character, which are normally hidden) in the parent of the working directory in long format
$*
The variable $*, is similar to $@, but does not preserve any whitespace, and quoting, so “File with spaces” becomes “File” “with” “spaces”.
$?
this contains the exit value of the last run command Exit status is a numerical value returned by every command upon its completion. As a rule, most commands return an exit status of 0 if they were successful, and 1 if they were unsuccessful.
$#
$# is the number of parameters the script was called with.
$$
The $$ variable is the PID (Process IDentifier) of the currently running shell. This can be useful for creating temporary files, such as /tmp/my-script.$$ which is useful if many instances of the script could be run at the same time, and they all need their own temporary files.
$!
The $! variable is the PID of the last run background process. This is useful to keep track of the process as it gets on with its job.
$0
the file name of the current script
$n
These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).
How to assign the output of a command to a variable in bash?
You need to use command substitution feature of bash. It allows you to run a shell command and store its output to a variable. To assign output of any shell command to variable in bash, use the following command substitution syntax: var=$(command-name-here) var=$(command-name-here arg1) var=$(/path/to/command) var=$(/path/to/command arg1 arg2) OR var=command-name-here
var=command-name-here arg1
var=/path/to/command
var=/path/to/command arg1 arg2
var=10; echo $var + 5
result: 10+5
What is a header file?
A header file is a file with extension .h which contains C function declarations and macro definitions and to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that come with your compiler. Both user and system header files are included using the preprocessing directive #include. It has following two forms: #include #include “file”
List some common headers in the standard C library.
- defines common mathematical functions - defines a boolean data type - defines core input and output functions - Defines numeric conversion functions, pseudo-random numbers generation functions, memory allocation, process control functions - defines string handling functions See: http://en.cppreference.com/w/c/header
How does the C preprocessor work?
The C preprocessor, often known as cpp, is a macro processor that is used automatically by the C compiler to transform your program before compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs. The C preprocessor is intended to be used only with C, C++, and Objective-C source code. In the past, it has been abused as a general text processor.
include
include tells the C compiler to find the standard header called and add it to this program. In C, you often have to pull in extra optional components when you need them. contains descriptions of standard input/output functions which you can use to send messages to a user, or to read input from a user.
printf
printf is the formatted printing function that is declared in the file stdio.h - which is why you had to #include that at the start of the program.
The header shall define the following symbolic constants, each of which expands to a distinct constant expression of the type: void (*)(int) whose value matches no declarable function.
stdlib.h is a standard C header that declares among other things the malloc(), calloc(), free() functions.
malloc.h
malloc.h is a non-standard header, found on many systems where it often defines additional functions specific to the malloc implementation used by that platform.
libraries vs header files
Header files declares things, like structs and function prototypes. Libraries contains the implementation, the compiled code. You link to librarie, and you #include header files.
scanf()
The scanf() function is the input method equivalent to the printf() output function - simple yet powerful. In its simplest invocation, the scanf format string holds a single placeholder representing the type of value that will be entered by the user.
storage classes in C:
A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. 1. auto 2. register 3. static 4. extern
auto storage class
auto is the default storage class for all local variables. auto can only be used within functions, i.e. local variables.
register storage class
register is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and cant have the unary ‘&’ operator applied to it (as it does not have a memory location). Register should only be used for variables that require quick access - such as counters. It should also be noted that defining ‘register’ goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register - depending on hardware and implimentation restrictions.
Variables which are used repeatedly or whose access times are critical may be declared to be of storage class register.
static storage classes
static is the default storage class for global variables. static can also be defined within a function. If this is done the variable is initalised at run time but is not reinitalized when the function is called. This inside a function static variable retains its value during vairous calls.
extern storage class
extern is used to give a reference of a global variable that is visible to ALL the program files. When you use ‘extern’ the variable cannot be initalized as all it does is point the variable name at a storage location that has been previously defined.
pwd.h
The header provides a definition for struct passwd, which includes the following members: char *pw_name user’s login name uid_t pw_uid numerical user ID gid_t pw_gid numerical group ID char *pw_dir initial working di rectory char *pw_shell program to use as shell The gid_t and uid_t types are defined as described in .
C preprocessor
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your program before actual compilation. It is called a macro processor because it allows you to define macros, which are brief abbreviations for longer constructs. The C preprocessor provides four separate facilities that you can use as you see fit: - Inclusion of header files. These are files of declarations that can be substituted into your program. - Macro expansion. You can define macros, which are abbreviations for arbitrary fragments of C code, and then the C preprocessor will replace the macros with their definitions throughout the program. - Conditional compilation. Using special preprocessing directives, you can include or exclude parts of the program according to various conditions. - Line control. If you use a program to combine or rearrange source files into an intermediate file which is then compiled, you can use line control to inform the compiler of where each source line originally came from.
CPP 1. Transformations made globally
- All C comments are replaced with single spaces. 2. Backslash-Newline sequences are deleted, no matter where. This feature allows you to break long lines for cosmetic purposes without changing their meaning. 3. Predefined macro names are replaced with their expansions
CPP2. Preprocessing directives
Preprocessing directives are lines in your program that start with #'. The
#’ is followed by an identifier that is the directive name. For example, #define' is the directive that defines a macro. Whitespace is also allowed before and after the
#’.
CPP3. Header files
A header file is a file containing C declarations and macro definitions (see section 1.4 Macros) to be shared between several source files. You request the use of a header file in your program with the C preprocessing directive #include'. - System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries. - Your own header files contain declarations for interfaces between the source files of your program. Each time you have a group of related declarations and macro definitions all or most of which are needed in several different source files, it is a good idea to create a header file for them. Including a header file produces the same results in C compilation as copying the header file into each source file that needs it. But such copying would be time-consuming and error-prone. With a header file, the related declarations appear in only one place. Both user and system header files are included using the preprocessing directive
#include’. It has three variants: 1. #include - This variant is used for system header files. It searches for a file named file in a list of directories specified by you, then in a standard list of system directories. You specify directories to search for header files with the command option -I' 2. #include "file" - This variant is used for header files of your own program. It searches for a file named file first in the current directory, then in the same directories used for system header files. The current directory is the directory of the current input file. It is tried first because it is presumed to be the location of the files that the current input file refers to. (If the
-I-‘ option is used, the special treatment of the current directory is inhibited.) 3. #include anything else - This variant is called a computed #include. Any `#include’ directive whose argument does not fit the above two forms is a computed include. The text anything else is checked for macro calls, which are expanded (see section 1.4 Macros). When this is done, the result must fit one of the above two variants–in particular, the expanded text must in the end be surrounded by either quotes or angle braces.
CCP4. Macros
A macro is a sort of abbreviation which you can define once and then use later. A simple macro is a kind of abbreviation. It is a name which stands for a fragment of code. Some people refer to these as manifest constants. Before you can use a macro, you must define it explicitly with the #define' directive.
#define’ is followed by the name of the macro and then the code it should be an abbreviation for. For example, #define BUFFER_SIZE 1020 defines a macro named BUFFER_SIZE' as an abbreviation for the text
1020’. You can also have macros that accept arguments - A macro that accepts arguments is called a function-like macro because the syntax for using it looks like a function call. Also, several simple macros are predefined. You can use them without giving definitions for them. They fall into two classes: standard macros and system-specific macros. Examples: __OPTIMIZE__ GNU CC defines this macro in optimizing compilations. It causes certain GNU header files to define alternative macro definitions for some system library functions. The C preprocessor normally has several predefined macros that vary between machines because their purpose is to indicate what type of system and machine is in use. example: unix
CPP5. Conditionals
In a macro processor, a conditional is a directive that allows a part of the program to be ignored during compilation, on some conditions. In the C preprocessor, a conditional can test either an arithmetic expression or whether a name is defined as a macro. A conditional in the C preprocessor resembles in some ways an if' statement in C, but it is important to understand the difference between them. The condition in an
if’ statement is tested during the execution of your program. Its purpose is to allow your program to behave differently from run to run, depending on the data it is operating on. The condition in a preprocessing conditional directive is tested when your program is compiled. Its purpose is to allow different code to be included in the program depending on the situation at the time of compilation. #if X == 1 … #elif X == 2 … #else /* X != 2 and X != 1*/ … #endif /* X != 2 and X != 1*/ Example:
The directives concerned are: #if, #ifdef, #ifndef, #elif,#else, #endif together with the preprocessor unary operator defined.
CPP6. Combining source files
One of the jobs of the C preprocessor is to inform the C compiler of where each line of C code came from: which source file and which line number.
CPP7. Invoking the C Preprocessor
Most often when you use the C preprocessor you will not have to invoke it explicitly: the C compiler will do so automatically. However, the preprocessor is sometimes useful on its own. The C preprocessor expects two file names as arguments, infile and outfile. The preprocessor reads infile together with any other files it specifies with #include'. All the output generated by the combined input files is written in outfile. Either infile or outfile may be
-‘, which as infile means to read from standard input and as outfile means to write to standard output. Also, if outfile or both file names are omitted, the standard output and standard input are used for the omitted file names. Some examples of commands options accepted by CPP: -C' Do not discard comments: pass them through to the output file. Comments appearing in arguments of a macro call will be copied to the output before the expansion of the macro call.
-Wall’ Requests both -Wtrigraphs' and
-Wcomment’ (but not -Wtraditional' or
-Wundef’). -I directory' Add the directory directory to the head of the list of directories to be searched for header files (see section 1.3.2 The
#include’ Directive). This can be used to override a system header file, substituting your own version, since these directories are searched before the system header file directories. If you use more than one -I' option, the directories are scanned in left-to-right order; the standard system directories come after.
-nostdinc’ Do not search the standard system directories for header files. Only the directories you have specified with -I' options (and the current directory, if appropriate) are searched.
-gcc’ Define the macros __GNUC__ and __GNUC_MINOR__. These are defined automatically when you use gcc -E'; you can turn them off in that case with
-no-gcc’.
What’s the freaking purpose of the C preprocessor?
it can equally well be though of as a separate program which transforms C source code containing preprocessor directives into source code with the directives removed.
Summarize the importance of the C preprocessor.
There are only a very few aspects that are really important.
The ability to define macros and function macros is very important, being widely used in almost every C program except the most trivial.
The conditional compilation has two important uses; one is the ability to compile with or without debugging statements included in a program, the other is to be able to select machine or application dependent statements.
Obviously, file inclusion is fundamentally important.
What is pipelining?
You can connect two commands together so that the output from one program becomes the input of the next program. Two or more commands connected in this way form a pipe.
What is the ‘grep’ command?
The grep program searches a file or files for lines that have a certain pattern. The syntax is:
$grep pattern file(s)
What does the sort command do?
The sort command arranges lines of text alphabetically or numerically.
What does the more command do?
A long output would normally zip by you on the screen, but if you run text through more or pg as a filter, the display stops after each screenful of text.
What is the GNU build system for?
1) Building, Porting, and Packaging Source Code.
What does the ps command do?
report a snapshot of the current processes.
What command from GNU build does the building?
make, or make all
What tools in GNU Build are for porting and packaging?
(autotools)
1) autoconf
2) automake
3) libtool
Name three advnaced packaging tools on Debian?
- dh_make: Debian Packaging
- dpkg: install/de-install
- aptitude/synatpic: dealswith software repositories
Explain this:
tar -zxvf test123.tar.gz
The tar extension is short for ‘tape archive. Tar files are used “To combine multiple files and/or directories into a single file”. The .gz extension tells us that the file is compressed and needs to be unzipped.
where
z– unzip
x– extract the file
v– verbose
f– forcefully done
If we have no Makefile to build our source files into a program what command do we need to run?
You need to run ./configure. This creates a Makefile based on the general state of your OS.
What does the ‘kill’ command do?
Use the kill command to send a signal to each process specified by a pid (process identifier). The default signal is SIGTERM (terminate the process).
The ./configure command turns
1) configure.ac into what?
2) and form what file does it create the Makefile?
1) Configure and aclocal.m4
2) Makefile.in (in for incomplete)
What does the top command do?
The top program provides a dynamic real-time view of a running system. It can display system summary information as well as a list of tasks currently being managed by the Linux kernel.
During the ./configure command configure.h.in
is turned into what/
Configure.h
The.in is removed becuase it is no longer incomplete
vmstat
vmstat reports information about processes, memory, paging, block IO, traps, and cpu activity.
What file does autoscan produce?
Autoscan produces configure.scan which must be renamed to configure.ac
free command
free is a command which can give us valuable information on available RAM in Linux machine.
What does configure.ac contain?
It contains special macros:
AC_Marcros for autoconf
AM_Mcros for automake
What is the difference between downloading from source and downloading from binaries?
Installing from source means you compile the souce code and then install.
Installing from binary means someone allready compiled it into binary and you just have to put it on your computer.
What is better? Installing from binary or from source? And why?
Fromsourceis better:
- ) It can be optimized for (for example) an Athlon processor whereas with binaries you’re stuck with it being compiled for whatever system the person who compiled it was running.
- ) Also, if you run a binary and it needs shared libraries, such as GTK, then you have to have the EXACT same version of the libraries on your system as those on the system the binary was compiled on.
In general, from source allows for more custom installation.
What is the target and what is the pre-requisite here?
all: prog 1 prog 2
The syntax requires that targets are onthe left and the targets dependencies are to it’s right.
What is a pointer?
A pointer is a value that designates the address (i.e., the location in memory), of some value.
Pointers are variables that hold a memory location – the location of some other variable. One can access the value of the variable pointed to using the dereferencing operator ‘*’. Pointers can hold any data type, even functions
Pointers are variables that don’t hold the actual data. Instead they point to the memory location of some other variable. For example,
int *pointer = &variable;
defines a pointer to an int, and also makes it point to the particular integer contained in variable.
The ‘*’ is what makes this an integer pointer. To make the pointer point to a different integer, use the form
pointer = &sandwiches;
Where & is the address of operator.
Often programmers set the value of the pointer to NULL (a standard macro defined as 0 or (void*)0 ) like this:
pointer = NULL;
This tells us that the pointer isn’t currently pointing to any real location. Additionally, to dereference (access the thing being pointed at) the pointer, use the form:
value = *pointer;
List some standard targets for a Makefile
- all
- clean
- uninstall
- install
- dist
- dist clean
*
A makefile is processed in two stages by the make command? Whatarethese stages?
- Compute a graph of dependencies
- Rebuild necessary targets
In a makefile what does $@ refer too?
prog1: prog1.0 circle.o
$(cc) $(LDFLAGS) %^ -o $@
The name of the target of a rule.
So $@ is short for prog1 in this case.
Struct
A data structure (“struct”) contains multiple pieces of data. Each piece of data (called a “member”) can be accessed by the name of the variable, followed by a ‘.’, then the name of the member. (Another way to access a member is using the member operator ‘->’).
The member variables of a struct can be of any data type and can even be an array or a pointer. One defines a data structure using the struct keyword. For example,
struct mystruct
{
int int\_member; double double\_member; char string\_member[25];
} variable;
variable is an instance of mystruct. You can omit it from the end of the struct declaration and declare it later using:
struct mystruct variable;
What does malloc do?
The malloc function returns a pointer to dynamically allocated memory (or NULL if unsuccessful). The size of this memory will be appropriately sized to contain the MyStruct structure.
What does $< refer too?
prog1: prog1.o circle.o
$(cc) $(LDFLAGS) $\< -o $@
The name of the first prerequisite of a rule.
In this case, $< is short for prog1.o
What does $^ refer too?
prog1: prog1.o circle.o
$(cc) $(LDFLAGS) $^ -o $@
The names of all prerequisites of a rule.
In this case, $^ refers to prog1.o and circle.o
What does the ar command do here:
ar -cr libname.a obj1.o obj2.o
ar -archiver, creates static libraries by grouping object files.
- c stands for create
- r stands for insert
Howdo we get the value of an object which a pointer p is pointing to?
*p
How do we get the address of an object which a pointer p is pointing to?
&p
If p and q are both pointer types is this legal?
p = q
Yes, becuase pointers are variables and can be assigned.
Without pointers what would be the problem with a function like this:
swap(a,b)
that simly swapped the values of a and b?
C is pass by value. unless you use pointers. Pointers allow you to change the address a variable points to (pass by reference) and this allows a function like swap(&a &b) to chnage the vlues outside it’s own scope.
Pointer deferencing
The pointer p points to the variable a.
To access a value to which a pointer points, the * operator is used. Another operator, the -> operator is used in conjunction with pointers to structures.
A short example is shown below.
int c, d;
int *pj;
struct MyStruct astruct;
struct MyStruct *bb;
c = 10;
pj = &c; /* pj points to c */
d = *pj; /* d is assigned the value to which pj points, 10 */
pj = &d; /* now points to d */
*pj = 12; /* d is now 12 */
bb = &astruct;
(*bb).m_aNumber = 3; /* assigns 3 to the m_aNumber member of astruct */
bb->num2 = 44.3; /* assigns 44.3 to the num2 member of astruct */
*pj = bb->m_aNumber; /* eqivalent to d = astruct.m_aNumber; */
When dereferencing a pointer that points to an invalid memory location, an error often occurs which results in the program terminating. The error is often reported as a segmentation error. A common cause of this is failure to initialize a pointer before trying to dereference it.
Here is an array called ‘a’
[h,e,l,l,o,]
Will this return something
‘a’?
Yes, if ‘a’ is an array then ‘a’ is the same as a[0] so it will return ‘h’
Canyou write this in another format?
array[3]
*(array + 3)
Are these identical?
- char a[] = hello;
and
- char *a = hello
No, they are different although they will give the same output.
- This creates a spacein the stack for storing something thesame size as ‘hello’ and then puts the contents of ‘hello’ into that spaceon the stack.
- Creating a pointer means that a points to the word ‘hello’ somewhere in read-only memory.
With the first option ‘hello’ is in read-write memory. In the second, it is not.
What is a c-string?
A c-string can be contrasted with a string literal.
The later is stored in read only memory as a result of this type of declaration and cannot be altered
char * p = “const cstring”;
A c-string can be altered becuase it is declared with an array which copies values from read-only memory into the arraywhich is stroed onthe stack(read-write)
char cstr[] = “c-string”;
malloc
The C function malloc is the means of implementing dynamic memory allocation. It is defined in stdlib.h or malloc.h, depending on what operating system you may be using.
free() in C
The corresponding call to release allocated memory back to the operating system is free. When dynamically allocated memory is no longer needed, free should be called to release it back to the memory pool.
Can you change the address of pointers and variables?
No, you can change where a pointer points, but a variables address is stroed statically and cannot be changed like this:
&var = new address.
What’s the point of malloc?
Sometimes it is not known at the time the program is written how much memory will be needed for some data. In this case we would want to dynamically allocate required memory after the program has started executing. To do this we only need to declare a pointer, and invoke malloc when we wish to make space for the elements in our array, or, we can tell malloc to make space when we first initialize the array. Either way is acceptable and useful.
So how do we malloc an array of ten ints like before? If we wish to declare and make room in one hit, we can simply say
int *array = malloc(10*sizeof(int));
We only need to declare the pointer; malloc gives us some space to store the 10 ints, and returns the pointer to the first element, which is assigned to that pointer.
Important note! malloc does not initialize the array; this means that the array may contain random or unexpected values! Like creating arrays without dynamic allocation, the programmer must initialize the array with sensible values before using it. Make sure you do so, too.
It is not necessary to immediately call malloc after declaring a pointer for the allocated memory. Often a number of statements exist between the declaration and the call to malloc, as follows:
int *array = NULL;
printf(“Hello World!!!”);
/* more statements */
array = malloc(10*sizeof(int)); /* delayed allocation */
/* use the array */
Name two ways in which memory can be allcated to an array?
- ) Statically at complile time
- ) Dynamically at run time
What arethe different ways we can initialize or fill up an array in C?
- ) We can loop with i++ and use the array as such a[i]
2) We can use i++ again, but using *(a+1)
3) We can write a[5] = {1,2,3} // 4,5 will equal zero
4) We canwrite a[] = {1,2,3} // Now size is of 3
Error-checking when using malloc
When we want to use malloc, we have to be mindful that the pool of memory available to the programmer is finite. As such, we can conceivably run out of memory! In this case, malloc will return NULL. In order to stop the program crashing from having no more memory to use, one should always check that malloc has not returned NULL before attempting to use the memory; we can do this by
int *pt = malloc(3 * sizeof(int));
if(pt == NULL)
{
fprintf(stderr, “Out of memory, exiting\n”);
exit(1);
}
Of course, suddenly quitting as in the above example is not always appropriate, and depends on the problem you are trying to solve and the architecture you are programming for. For example if program is a small, non critical application that’s running on a desktop quitting may be appropriate.
calloc in C
The calloc function allocates space for an array of items and initilizes the memory to zeros. The call mArray = calloc( count, sizeof(struct V)) allocates count objects, each of whose size is sufficient to contain an instance of the structure struct V. The space is initialized to all bits zero. The function returns either a pointer to the allocated memory or, if the allocation fails, NULL.