abmj0
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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...

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully