Lab00: Introduction to C programming
(The monospace font size defaults to 12 on IDA's firefox installation. If the code on this page is difficult to read change your firefox settings in Edit->Preferences->Content->Advanced (Swedish: Redigera->Inställningar->Innehåll->Avancerat).)1. Hello, world. [10 min]
Everytime you start to work with a new programming language, it is tradition to make the "Hello, world" program. Create it, compile it, and run it.2. debugthis
First try to understand the program below and spot the bug, and fix it if you can.
Run the program in ddd or gdb to find the row where the segmentation fault
occurs. You must first compile it with gcc -g
for this to work.
Copy the follwing text and save and compile it:
#include <stdio.h>
int main(int argc, char ** argv)
{
char str[] = "sihtgubed";
char *stri = &str[8];
char *buf[9];
char **bufi, **bufend;
bufi = buf;
bufend = &buf[9];
while (bufi != bufend){
*bufi = stri;
bufi++;
stri--;
}
while (bufi != buf){
*(*bufi) -= 32;
bufi--;
}
while (bufi != bufend){
printf("%c", **bufi);
bufi++;
}
}
N.B. This is a silly and not very pretty program. Hint: Check an ASCII table (for example by typing man ascii in the console).
You need to demonstrate this part (2) for your assistant!
3. Create a linked list of integers.
Create a linked list with the following functions:
void append(struct list_item *first, int x); /* puts x at the end of the list */
void prepend(struct list_item *first, int x); /* puts x at the beginning of the list */
void print(struct list_item *first); /* prints all elements in the list */
/* input_sorted: find the first element in the list larger than x
and input x right before that element */
void input_sorted(struct list_item *first, int x);
void clear(struct list_item *first); /* free everything dynamically allocated */
Hint1: You need to use malloc
(and
free
of course) and a struct list_item
that contains a pointer to the same struct:
struct list_item {
int value;
struct list_item * next;
};
Hint2: Implementing the list will be easier if you make
first
be a static head element that does not contain
any real data. (Because there are fewer exceptions if you know
first
is never NULL.) Your main
can start like this:
int main( int argc, char ** argv)
{
struct list_item root;
root.value = -1; /* This value is always ignored */
root.next = NULL;
4. Create a test program
Write a piece of code that tests you linked list implementation. You should test all the relevant cases including, creation, insertion (all different types), printing, and clearing. Try several different orders of these functions (including printing after clearing the list). UseValgrind
to make sure you have got no memory leaks.
You can use the following command:
% valgrind --tool=memcheck --leak-check=yes your-program
You need to demonstrate this part (4) to your assistant!
Page responsible: Klas Arvidsson
Last updated: 2025-01-24