---
# System prepended metadata

title: Week 1 - Memory

---

# Week 1 - Memory

## Team

Team name: D&Z
Date:2022-02-09

Members
Zowie Zijdemans
Dilawar Faiz
| Role                                                                                                                                                                          | Name |
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------|
| **Facilitator** keeps track of time, assigns tasks and makes sure all the group members are heard and that decisions are agreed upon.                                             |Zowie Zijdemans|
| **Spokesperson** communicates group’s questions and problems to the teacher and talks to other teams; presents the group’s findings.                                              |Dilawar Faiz|
| **Reflector** observes and assesses the interactions and performance among team members. Provides positive feedback and intervenes with suggestions to improve groups’ processes. |Zowie Zijdemans|
| **Recorder** guides consensus building in the group by recording answers to questions. Collects important information and data.                                                   |Dilawar Faiz|

## Activities
Make sure to have the activities signed off regularly to ensure progress is tracked.

Set up a project in CLion to write the small programs needed in some of the activities.

### Activity 1: Memory usage - the sizeof operator
 Fill out the table below
• Run the program you’ve used to obtain the data type sizes in the online compiler explorer.
Do you see any differences in the sizes reported?

Yes the sizes differ from 1 to 16.

• Does the size of a pointer depend on its type? Why (not)?
No it doesn't depend on the type. It depends on how many bits your compiler is.


Record your answer here
```C
#include <stdio.h>

int main()
{

    printf("char=%lu\n", sizeof(char));
    printf("short int=%lu\n", sizeof(short int));
    printf("int=%lu\n", sizeof(int));
    printf("long int=%lu\n", sizeof(long int));
    printf("floatt=%lu\n", sizeof(float));
    printf("double=%lu\n", sizeof(double));
    printf("long double=%lu\n", sizeof(long double));
    
    printf("char*=%lu\n", sizeof(char*));
    printf("int*=%lu\n", sizeof(int*));
    printf("float*=%lu\n", sizeof(float*));
    printf("double*=%lu\n", sizeof(double*));
    printf("void*=%lu\n", sizeof(void*));
    return 0;
}   
```
### Activity 2: Array and structure sizes
This is how you include code listings in your markdown document:
```C
typedef struct {
	char name[80];
	int age;
} person_t;

void size_array(int array[]) {
	printf("Size of array parameter: %lu\n", sizeof(array));
}

void size_struct(person_t p) {
	printf("Size of p parameter: %lu\n", sizeof(p));
}

int main() {
	int array[10];
	person_t bob = {.name = "Bob", .age = 22};
	
	printf("Size of int array: %lu\n", sizeof(array));
	printf("Size of person_t structure: %lu\n", sizeof(bob));
	
	size_array(array);
	size_struct(bob);
}
```
The character size van een structure veranderd niet, het blijft 84 bits (80 bits voor de character array en 4 bits voor de interger age). Maar de int array is wel verschillend. want de een word doorgeven via een functie. 
### Activity 3: Memory addresses

```C
#include <stdio.h>

int main( void )  {
	int a = 0xA0B0C0D0;
	short int b = 0x7856;
	const char * s = "Hello!";
	char buf[] = "Pointer";
	short int c = 0x3412;

	printf("int a: %p\n", (void*) &a);
	printf("short int b: %p\n", (void*) &b);
	printf("const char *s: %p\n", (void*) &s);
	printf("char buf[]: %p\n", (void*) buf);
	printf("short int c: %p\n", (void*) &c);
    printf("string s first char: %p\n", (void*) &s[0]);
}	
```
Record your answer here
•Add a printf statement to print the memory address of the first character of the "string"
s. Are the characters of the string "Hello" stored near the variables a, b, s, and c?

No they are not stored near the other variables

• Are the variables layed out in a contiguous way in memory, or are there gaps between
them?

There are gaps between them


### Activity 4: Observing automatic lifetime

```cpp
#include <stdio.h>


int add(int a, int b) {
     int c = a + b;
     printf("Memory adress a: %p\n Memory adress b:%p\n Memory adress c: %p\n\n", a, b, c);
     return c;
     }

 int mul(int x, int y) {
     int z = x * y;
     printf("Memory adress x: %p\n Memory adress y:%p\n Memory adress z: %p\n\n", x, y, z);

     return z;
     }

 int main( void ) {
     printf("%d\n", mul(add(3, 4), add(1, 5)));
     }
  ```   
    output:
    Memory adress a: 0000000000000001
    Memory adress b: 0000000000000005
    Memory adress c: 0000000000000006

    Memory adress a: 0000000000000003
    Memory adress b: 0000000000000004
    Memory adress c: 0000000000000007

    Memory adress x: 0000000000000007
    Memory adress y: 0000000000000006
    Memory adress z: 000000000000002A

42
     
### Activity 5: Observing the stack
int a uses the same address as int x and y
```c=
#include <stdio.h>

int poly(int a) {
    printf("a=%p\n", a);
    int b = a * (a + 1);
    printf("b=%p\n", b);
    return b / 2;
}

int add_polys(int x, int y) {
    printf("x=%p\n", x);
    printf("y=%p\n", y);
    int bx = poly(x);
    int by = poly(y);
    printf("bx=%p\n", bx);
    printf("by=%p\n", by);
    return bx + by;
}

int main( void ) {
    printf("%d\n", add_polys(42, 24));
}
```

Record your answer here

### Activity 6: Leaking local addresses

De eerste waarde is 42 omdat er in de functie ptr_amswer gelijk word gezet aan de adress van "answer = 42",
De tweede geeft 24 omdat er een array is in de functie. En een array en pointer werkt hetzelfde met memories dus ptr_answer krijgt de waarde van de eerste integer value van de array.

### Activity 7: Memory addresses of local variables
• Which warnings and / or errors does the compiler give when compiling this program?
note: declared here 6 |     int array[10];
undefined reference to `do_some_work(int*, int)
• What do these warnings and / or errors mean?
?
• Does this approach to create an array at runtime work? Why (not)?
No it doesn't work

### Activity 8: Using malloc

```cpp

#include <stdio.h>
#include <stdlib.h>

int* allocate_memory (int count){
    return malloc(count * sizeof(int));

}
int main( void ) {


    unsigned long *a;
    a = (unsigned long*) malloc(sizeof (unsigned long [1]));

    float *b;
    b = (float*) malloc(sizeof (float [256] ));

    printf("%p\n", allocate_memory(a));
    printf("%p\n", allocate_memory(b));
```
    
### Activity 9: Using allocated memory as an array
• How many int elements can be stored in the allocated block of memory?
20 int element can be stored in the allocated block of memory
• What happens when you perform an out-of-bounds access to an array that is stored in
the value will be 0

dynamically allocated memory?
• What is the problem in the program listed below, and how can it be fixed?
Record your answer here

### Activity 10: Infinite memory?

the programma chrasht omdat er niet genoeg memory meer over is daarom is er ook een 0 aan het einde van de code. En er waren 209 x 8 bits geprints
### Activity 11: Fixing a memory leak

```cpp
#include <stdio.h>
#include <stdlib.h>

const int SIZE = 512;

int main( void ) {
    char *str = (char*) malloc(sizeof(char[SIZE]));

    printf("before: %lu \n", str);


    while (str == NULL) {
        str = malloc(SIZE);

    }
    if (str != NULL) {
        free(str);
    }
    printf("after free :%lu",str);
return 0;
}
```

uitkomst:
before: 12326064
after free : 12326064
de memory is geleegd want na het printen is dezelfde data over omdat je met free de gebruikte datat hebt geleegd
### Activity 12: Dangerous `free`s

Als je de free functie gebruikt zonder een malloc dan krijg je een sigtrap error op je compiler. Dat komt omdat je free niet kan gebruiken zonder malloc. Tenzij het een NULL is want Free functie gebruikt void* en daarom kan een null ook gebruikt worden.
### Activity 13: Using realloc

Record your answer here
10 keer moet de free functie gebruik worden.

### Activity 14: Using a dynamically sized buffer

Record your answer here
c```
#include <stdio.h>

int main( void ) {
    char *ptr = NULL;
    unsigned long capacity = 20;
    ptr = realloc(ptr, sizeof(char[capacity]));
    if (!ptr){
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

     FILE *file = fopen("input.txt", "r");
     if (!file) {
         fprintf(stderr, "Error opening file\n");
         return 1;
     }

     unsigned long count = 0;
     int c = fgetc(file);
     while (c != EOF) {
         /* re-allocate memory pointed to by ptr if count == capacity
         * don't forget to check if the pointer returned by realloc is not NULL
         */
         if(count==capacity){
             capacity= capacity*1.5;
             ptr = realloc(ptr, sizeof(char[capacity]));
         }
         ptr[count++] = (char) c;
         c = fgetc(file);
     }
 }



## Looking back

### What we've learnt

Stack vs Heap
In onze eigen woorden: Stack is een deel in de memory dat is bedoeld voor snelle simpele waarde die je op een specifiek moment gebruikt.
En heap is bedoelt voor complexere waardes die de programmeur zelf in de hand heeft door middel van malloc realloc en free 
### What were the surprises

\
### What problems we've encountered

We hadden moeite met het gebruiken van de free functie omdat we eerst niet wisten wanneer we die moesten gebruiken
### What was or still is unclear

We weten nog steeds niet zo goed wanneer we de malloc realloc en free functies het best kunnen gebruiken tijdens het programmeren

### How did the group perform?

Het samenwerken ging wel prima. We hadden de vragen verdeeld en aan het eind controleerde we oplossing. En als we vragen hadden tussendoor vroeg je dat.




> Written with [StackEdit](https://stackedit.io/).
