Snoopehz
    • 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
    # A1 1. Kawin Feng 525253 2. Andreas Andreou 507675 # Q1 * What are the memory address ranges of both arrays? Address of integers: 0x3046f86d0 Address of the doubles: 0x3046f76d0 * Do these memory address ranges overlap? The memories do overlap * Does the lifetime of the two arrays overlap? Why (not)? The life time of the arrays do overlap because sum_ints is called inside of the function of mul_double * How much memory does the program need to store the two arrays? Size of the doubles: we need total of 8192 in bytes for the array of doubles Size of the integers: we need total# of 4096 in bytes for the array of integers # Q2 * What are the memory address ranges of both arrays? Address of integers: 0x3095ff6a0 Address of the doubles: 0x3096006d0 * Do these memory address ranges overlap No they do not overlap * Does the lifetime of the two arrays overlap? Why (not)? Yes they do overlap because double doubles[1024] = {sum_ints()}; so the sum_ints is called inside the doubles array * How much memory does the program need to store the two arrays? Size of the doubles: 8192 Size of the integers: 4096 # Q3 * Which warnings and / or errors does the compiler give when compiling this program?error: no newline at end of file 1.error: address of stack memory associated with local variable 'array' returned 2.error: no newline at end of file * What do these warnings and / or errors mean? The first one means that the memory of the array is not available for use because its already occupied The second is that you can not return a vreiable from a void function * Does this approach to create an array at runtime work? Why (not)? The array is created in the program on run time but it doesnt work becasue its void and its not used in the main program function # Q4: include <stdio.h> include <malloc.h> int* allocate_memory(int count){ int skata=(int)malloc(count*sizeof(int)); if (skata==NULL){ return NULL; } return skata; } int main() { int count; unsigned long *p; p=( unsigned long *)malloc(sizeof(unsigned long)); float *d[256]; d[256]=(float*)malloc(256*sizeof(float)); allocate_memory(count); free(p); free(d); free(count); return 0; } # Q5 #include <stdio.h> #include <stdlib.h> int main(){ char *x=(char*) malloc(0); if(x==NULL) {printf('Fail');} else{printf('successful');} free(x); return 0; } * What does the call to malloc return? A big number that means nothing -25874136978 * 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? The system may crush or contain nonsense thats because the memory was used previsule and the data do not get over writen but corrapt the stucture * Is it possible to allocate a block of memory that has a negative size? Its not possible to alocate a memory with negative size # Q6 * How many int elements can be stored in the block of memory allocated by the create_array function? As we know int have a size of 4 bytes so the amount of int veriables that can be stored are 24(size_t capacity)/4 * What happens when you perform an out-of-bounds access to an array that is stored in dynamically allocated memory? It may crash the system,corrupt data or overwrite memory.Either way is not a good outcome and the prefered outcome is to crash the program because if not it may be hard to find out the error * What are the problems in the program listed below, and how can they be fixed (Includethe fixed program into your logbook) 1. The malloc is not alocating enough memory to store 24 int(capacity) it can store 24 bytes 2. The for loop starts from 1 and not from 0 as it should so the last value of the array is out of bounce 3. Farthermore the malloc function returns null if it fails to alocate memory and because the program does not check for this a null pointer will crush the program #include <stdio.h> #include <stdlib.h> int * create_array(size_t capacity) { int *ptr = (int*) malloc(capacity * sizeof(int)); return ptr; } int main(void) { const size_t capacity = 24; int *array = create_array(capacity); if (array == NULL) { fprintf(stderr, "Failed to allocate memory\n"); return 1; } for (size_t i = 0; i < capacity; i++) { array[i] = 42; } for (size_t i = 0; i < capacity; i++) { printf("array[%zu] = %d\n", i, array[i]); } free(array); return 0; } # Q7 The program listed below uses malloc to dynamically allocate arrays that can hold 2^10 ints,but it does not release this memory. Fix the program by calling free at the right place to releasethe allocated memory. Include the fixed program in your logbook, and describe the changes you have made to fix it. 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int main(void) { 5 const int size = 1024 * 1024; 6 for (int i = 0; i < size; ++i) { 7 int * ptr = (int*) malloc(sizeof(int[size])); 8 if (ptr != NULL) ptr[0] = 0; 9 free(ptr); 10} 11 12 puts("All done!"); 13 } # Q8 1. If we call free on a pointer that was not alocated by maloc the program may crash,have the wrong outcome or memory corruption 2. If we call free on a pointer that is NULL the function does complitly nothing because free is used to free memory thats alocated # Q9 * Of the 1000(is 10000 is wrong in the document) calls to realloc, how often is the memory reallocated to another memory address? The memory is alocated every time the loop is activated in this instance 10000 times and it alocates every time 1024 float numbers # Q10 #include <stdio.h> #include <stdlib.h> #include <assert.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 = (char*) 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) { capacity = capacity * 2; // increase capacity char *ptr1 = (char*) realloc(ptr, capacity*sizeof(char)); if (ptr1 == NULL) { // check if reallocation worked fprintf(stderr, "Memory reallocation failed\n"); free(ptr); return 1; } ptr = ptr1; } ptr[count++] = (char) c; // store current character c = fgetc(file); // read next character from file } int freq = 0; for (size_t i = 0; i < count; ++i) { if (ptr[i] == 'g') { freq++;} } assert(freq == 1176575); free(ptr); // release the memory printf("%d",freq); return 0; }

    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