Lab 2 - C programming in the UNIX command line. Detecting memory problems with valgrind.

 

 

C programming basics

Edit code (use extention .c to enable syntax highlighting): >> vi helloworld.c  

Compile/debug: >> gcc -Wall -o hello helloworld.c

Run: >> ./hello

 

 

 

Consulting system/C functions documentation

Manual sections can be seen by typing command man man  


1 User Commands

2 System Calls

3 C Library Functions

...


We identify in which section is the function we want to document about. Example, printf is a C Library Function, so will be in section 3:

>> man 3 printf

 This will show us the C printf function usage, parameters type and return value, required libraries etc.

 Another way to identify the manual section is to use the   whatis command:

>> whatis printf

printf (1) - format and print data
printf (3) - formatted output conversion
printf (1posix) - write formatted output
printf (3posix) - print formatted output

 

 

 

Debugging with gdb (Optional at this stage)

Compile and debug are usually performed with gcc.

But when errors issue at runtime (ex. we get Segmentation fault  :(((  ), we need more complex mechanisms.

One primitive way is placing printf("Checkpint no X \n"); around the code, to see how far it gets (number the printf text X=1, 2, 3...!).

A more elegant (but maybe complex way) is using gdb - might prove useful after lab 6.

 

Introduction to gdb: https://www.youtube.com/watch?v=bWH-nL7v5F4

                               or      6 Steps guide

Compile with option -g : >> gcc -Wall -g helloworld.c

>> gdb a.out

 

Short version of the commands:

 

 

 

Detect memory (allocation/deallocation) issues with valgrind

 

Malloc and free

 

void*malloc(size_t size)

Syntax:

ptr = (cast-type*) malloc(byte-size)

Example:

       int* ptr; //we want this to be an array of 100 integer numbers

 ptr = (int*) malloc(100 * sizeof(int));

//Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory.

//And, the pointer ptr holds the address of the first byte in the allocated memory.

       free(ptr);



Typedef pointer example:
typedef struct

{
char name[21]; char city[21]; char state[3]; } NewType; typedef NewType * NewTypePointer; NewTypePointer r; r = (NewTypePointer)malloc(sizeof(NewType));

 

Valgrind

>> valgrind ./myexecutable 

 

 

Problem 0. Compile this program and verify using valgrind.

 

 

Problem 1. Write a C programm which creates a 4 dimensional matrix with dimension read from keyboard.Populate the matrix with 1 everywhere then calculate the sum of all numbers. Deallocate all allocated memory at the end. Use valgrind to verify memory allocated is freed.

(a possible solution is presented below)

Valgrind output:

==30792== Memcheck, a memory error detector

==30792== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.

==30792== Using Valgrind-3.6.0 and LibVEX; rerun with -h for copyright info

==30792== Command: ./m4d

==30792==

d1 = 1

d2 = 2

d3 = 3

d4 = 4

sum = 24

==30792==

==30792== HEAP SUMMARY:

==30792==     in use at exit: 0 bytes in 0 blocks

==30792==   total heap usage: 10 allocs, 10 frees, 168 bytes allocated

==30792==

==30792== All heap blocks were freed -- no leaks are possible

==30792==

==30792== For counts of detected and suppressed errors, rerun with: -v

==30792== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)

 

 

Problem 2. a. Consider a text file storing a matrix as follows: the numbers of rows and columns are on the first line separated by space, and on the subsequent lines, are the elements of the matrix separated by space. 

b. Read a matrix of integers from a text file and display to it in the console.

                                                     i.     Explain double pointers

                                                   ii.     Explain two-dimensional matrix allocation and deallocation

                                                  iii.     Compile gcc -Wall -g -o matrix-from-text matrix-from-text.c

                                                  iv.     Run ./matrix-from-text m.txt

                                                   v.     Run with valgrin as valgrind ./matrix-from-text m.txt

 

c. Store the matrix in a binary file.

                                                     i.     Compile gcc -Wall -g -o matrix-to-binary matrix-to-binary.c

                                                   ii.     Run ./matrix-to-binary m.txt m.bin

                                                  iii.     Run with valgrin as valgrind ./matrix-to-binary m.txt m.bin

 

 

d. Verify the binary file generated by the program by displaying it in the console using command xxd m.bin

 

e. Load the matrix form the binary file and display it in the console.

                                                     i.     Compile gcc -Wall -g -o matrix-from-binary matrix-from-binary.c

                                                   ii.     Run ./matrix-from-binary m.bin

                                                  iii.     Run with valgrin as valgrind ./matrix-from-binary m.bin

 

Problem 3: Write a C program that receives as arguments several integer numbers and computes their average, min and max. You may use atoi().
The following program accepts any number of command-line arguments and prints them out:

 

 

Problem 4: Write a C program that reads strings, stores them in an array and sorts them and prints them sorted.

 

Homework 1: Practice debugging C rograms using cmd line tools: vim, gcc, (optional gdb).

Homework 2: Practice identifying memory leks using valgrind (simulate scenarios that are missing free(buffer) or close(file) lines).

Homework 3: Read more in man sections 2 and 3 about the following C functions (and corresponding c libraries required - header files):