---
# System prepended metadata

title: Week 1 - Memory

---

# Week 1 - Memory

## Team

Date:

Members:
- Ahmed Al-Ganad
- Saif Ba Madhaf

## 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.

### Before you start

In your projects, make sure that the `CMakeLists.txt` file contains the following line, so that potential problems appear in the "Messages" tab:

> ```text
> target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -pedantic -Werror)
> ```

Make sure to check the messages after building.

### Activity 1: Printing memory addresses - I

Give the memory address ranges of the two arrays, `integers` and `doubles`, in the code listed below.
Explain why these ranges do or do not overlap.

This is how you include code listings in your markdown document:
```C
#include <stdio.h>

int sum_ints(void) {
	int integers[1024] = {1};
	for (int i = 1; i < 1024; ++i) integers[i] = integers[i - 1] + 1;
	return integers[1023];
}

double mul_doubles(int init) {
	double doubles[1024] = {init};
	for (int i = 1; i < 1024; ++i) doubles[i] = doubles[i - 1] * 0.999;
	return doubles[1023];
}

int main(void) {
	double result = mul_doubles(sum_ints());
	printf("Result = %lf\n", result);
}
```
1. What are the memory address ranges of both arrays? 
it differs when compiled because it is saved on the stack.
2. Do these memory address ranges overlap? Yes, they do.
3. Does the lifetime of the two arrays overlap? They do not, because they never get executed at the same time.
4. How much memory does the program need to store the two arrays? 12,288 bytes.

### Activity 2: Printing memory addresses - II

1. The memory address of the arrays differ everytime it compiles.
2.  Yes, They do overlap
3. The life time of the arrays do not overlap because they are not called within the same function.
4. about 1200 bytes
The double array starts before the ints array and ends after it. So they do overlap.

```C
#include <stdio.h>

int sum_ints(void) {
	int integers[1024] = {1};
	for (int i = 1; i < 1024; ++i) integers[i] = integers[i - 1] + 1;
     printf("The address of the first element in ints is: %p, Last element: %p\n",
           (void*)&integers[0], (void*)&integers[1024]);
	return integers[1023];
}

double mul_doubles(void) {
	double doubles[1024] = {sum_ints()};
	for (int i = 1; i < 1024; ++i) doubles[i] = doubles[i - 1] * 0.999;
    printf("The address of the first element in floats is: %p, Last element: %p\n",
           (void*)&doubles[0], (void*)&doubles[1024]);
	return doubles[1023];
}

int main(void) {
	double result = mul_doubles();
	printf("Result = %lf\n", result);
}
```


### Activity 3: Using data that is no longer alive

- Which warnings and / or errors does the compiler give when compiling this program?
Ans: Address of stack memory associated with local variable 'array' returned
-  What do these warnings and / or errors mean?
Ans: It tells us that the code is attempting to return a pointer to memory that was allocated on the stack, which is only valid within the scope of the function. Once the function returns, the memory is no longer valid, and using the pointer can lead to undefined behavior or a crash.
- Does this approach to create an array at runtime work? Why (not)?
Ans: No it does not work beacause the array is allocated in the stack, which means that the array is valid within the function, which means when the function returns, the memory used by the array is deallocated, and the pointer to the array becomes invalid. We can use the fuction malloc to allocate the array in the heap, so that it can be valid when called in the main fuction.

```c
#include <stdio.h>

int * create_array(void) {
	int array[10];
	return array;
}

void print_array(int values[], size_t size) {
	printf("[%d", values[0]);
	for (size_t i = 1; i < size; ++i) printf(", %d", values[i]);
	printf("]\n");
}

int main(void) {
	int * values = create_array();
	for (int i = 0; i < 10; ++i) values[i] = i + 1;
	print_array(values, 10);
}
```

### Activity 4: Using malloc
```c
#include <stdio.h>
#include <stdlib.h>

int* allocate_int(size_t count);

int main(void) {
    // Allocate memory for one unsigned long number
    unsigned long* ul_ptr = (unsigned long*) malloc(sizeof(unsigned long));

    if (ul_ptr == NULL) {
        fprintf(stderr, "Out of memory");
        exit(EXIT_FAILURE);
    }

    // Allocate memory for 256 float numbers
    float* float_ptr = (float*) malloc(sizeof(float) * 256);

    if (float_ptr == NULL) {
        fprintf(stderr, "Out of memory");
        exit(EXIT_FAILURE);
    }

    int* int_ptr = allocate_int(10);

    if (int_ptr == NULL) {
        fprintf(stderr, "Out of Memory");
        exit(EXIT_FAILURE);
    }
    // Free allocated memory form the heap to avoid memory leakage
    free(ul_ptr);
    free(float_ptr);
    free(int_ptr);
    // Assigning the variables to NULL to get a segmentation failure if we call them out of thier scope
    ul_ptr = NULL;
    float_ptr = NULL;
    int_ptr = NULL;

    return 0;
}

int* allocate_int(size_t count) {
    int* int_ptr = (int*) malloc(sizeof(int) * count);

    if (int_ptr == NULL) {
        fprintf(stderr, "Out of Memory");
        exit(EXIT_FAILURE);
    }
    return int_ptr;
}

```
### Activity 5: Allocating zero bytes

```c
int main(void){
    void* ptr = malloc(0);
    int* int_ptr = (int*) ptr;
    *int_ptr = 42;
    if(ptr == NULL){
        fprintf(stderr, "No Memory allocated");
        exit(EXIT_FAILURE);
    }
    printf("Pointer address: %d", *int_ptr);
    free(ptr);
    return 0;
}
```
- What does the call to malloc return?
Ans: It returns a valid address, however the pointer point to an address that has a size of 0.
-  What happens if you try to store data in the block of memory obtained by malloc (by
storing a value at the address that was returned), and why does that happen?
Ans: The output of the variable stored in zeroed malloc can be unpredictable it can print out a segmentation fault or curropt memory, however in my case with the code written above the output was surprisingly printed out correctly.
- Is it possible to allocate a block of memory that has a negative size?
Ans: No, this gives a compilation error. Because malloc takes size_t as an arguement, and thus it can not be negative.
### Activity 6: Using allocated memory as an array

- How many int elements can be stored in the block of memory allocated by the
create_array function?
Ans: It depends on the capacity paramemter passed to the function create_array.
- What happens when you perform an out-of-bounds access to an array that is stored in
dynamically allocated memory?
Ans: It will cause undefined behaviour and could lead to memory leakage.
- • What are the problems in the program listed below, and how can they be fixed (Include
the fixed program into your logbook)?
Ans: The program does not check if the memory allocation was successful before attempting to acces the file. The program also tries to access memory outside the range given. The program does not free the allocated memory after using it which might result in memory leakage.

```c
int * create_array(size_t capacity) {
	int *ptr = (int*) malloc(capacity);
	return ptr;
}

int main( void ) {
	const size_t capacity = 24;
	int * array = create_array(capacity);
    if (array == NULL){
        fprintf(stderr, "No Memory allocated");
        exit(EXIT_FAILURE);
    }
	for (size_t i = 1; i <= capacity; i++) array[i] = 42;
	for (size_t i = 1; i <= capacity; i++) {
		printf("array[%zu] = %d\n", i, array[i]);
	}
    free(ptr);
}

```

### Activity 7: Fixing a memory leak

```c
int main(void){
    const int size = 1024 * 1024;
    for (int i = 0; i < size; ++i){
        int * ptr = (int*) malloc(sizeof(int[size]));
        if (ptr != NULL) ptr[0] = 0;
        free(ptr); //We free the allocation here within the scope of ptr
    }
    puts("All done!");
}
```

### Activity 8: Dangerous `free`s

We observed that an address that is automatically allocated in the stack can not be freed. Also a pointer that has the value of NULL does not need to be deallocated. When we tried to print the address of ptr_null
```c
printf("*null_ptr = %p", (void*)null_ptr);
```
 this displays in the console * null_ptr = (nil)

### Activity 9: Using realloc

Record the answer to the activity's questions here.

```c
#include <stdio.h>
#include <stdlib.h>
int main( void ) {
    float *grades = NULL;
    size_t capacity = 1024;
    int count_same_address = 0;

    for (int count = 0; count < 1000; capacity += 1024, ++count) {
        float *old_address = grades;
        float *new_grades = (float*)realloc(grades, sizeof(float[capacity]));
        if (new_grades != NULL) {
            grades = new_grades;
            if (old_address == new_grades) {
                count_same_address++;
            }
        }
    }
    
    printf("Number of times the memory was expanded: %d\n", count_same_address);
    free(grades);
    return 0;
}

```
Ans: added a variable expanded to count how often the memory was expanded in place.


### Activity 10: Using a dynamically sized buffer

Download the project for this activity from Blackboard.

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

int main(void) {
    char* ptr = NULL;       // the memory address of the array
    size_t capacity = 20;   // the initial capacity of the array
    size_t count = 0;       // the number of actual values stored in the array

    ptr = malloc(capacity * sizeof(char));  // allocate memory
    if (ptr == NULL) {      // check if allocation worked
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    FILE* file = fopen("E.coli.txt", "r");
    if (file == NULL) {     // check if file was opened
        fprintf(stderr, "Error opening file\n");
        return 1;
    }

    int c = fgetc(file);    // read next character from file
    while (c != EOF) {
        if (count == capacity) {    // if the current capacity is reached
            capacity *= 2;          // double the capacity
            char *ptr_ = realloc(ptr, capacity * sizeof(char)); // reallocate memory
            if (ptr_ == NULL) {      // check if reallocation worked
                free(ptr);
                fprintf(stderr, "Memory reallocation failed\n");
                return 1;
            }
            else{
                ptr = ptr_; // Teachers code
            }
        }
        ptr[count++] = (char)c;     // store current character
        c = fgetc(file);            // read next character from file
    }

    // count how many 'g's are in the file
    int freq = 0;
    for (size_t i = 0; i < count; ++i) {
        if (ptr[i] == 'g') {
            freq++;
        }
    }
    printf("The frequency of 'g' is: %d\n", freq);
    free(ptr);              // release the memory
    return 0;
}
```


## Looking back

### What we've learnt

Formulate at least one lesson learned.
We learned alo about memory in C and where are they allocated. We learned about the Automatic memory which is stored in the stack. Also about the static memory. And finally, the most interesting dynamic memory which is stored on the heap. We also learned alot about a variable's lifetime and it's scope.

### What were the surprises

Knowing that we can allocate memory manually and then release it to use it somewhere else was so interesting.  
### What problems we've encountered

Using Realloc is somewhat complicated.

### What was or still is unclear

Fill in...