Thread: Dynamic allocation (I thought it would crash)

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User Baaaah!'s Avatar
    Join Date
    Oct 2005
    Location
    UK
    Posts
    23

    Dynamic allocation (I thought it would crash)

    I've been trying to learn a bit about dynamic allocation in my noobish way, and I decided to see what would happen if I deliberately tried to cram too much data into a memory block that is too small to contain it all. Ironically the program seems to function correctly, printing out the full array, even though I've tried to make it overload. I can't figure out why.

    Code:
    /* Dynamic memory allocation */
    
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
       char size[5];   // Array deliberately set too small
       int *memory_block;
       int i;
       char word[] = "abcdefghijklmnopqrs";
       char c;
    
       /* Allocate memory defined by char array 'size' */
       memory_block = malloc(sizeof(size));
       
       /* Check for allocation failure */
       if(memory_block == NULL)
       {
          printf("Allocation Failed.\n");
          exit(EXIT_FAILURE);
       }else
          printf("Memory Allocated.\n");
    
       /* Copy data stored in 'word' into 'memory_block' */
       for(i = 0; word[i]; i++)
       {
       memory_block[i] = word[i];
       printf("%c\n", memory_block[i]);   
       }
    
       /* Return memory to heap */
       free(memory_block);
    
       /* Exit */
       printf("Press 'q' to exit:");
       if((c = _getch()) == 'q')
          return 0;
    }
    Output:

    Memory Allocated
    a
    b
    c
    d
    e
    f
    ............
    s
    Press 'q' to exit:
    Last edited by Baaaah!; 11-30-2005 at 05:39 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A question related to dynamic memory allocation
    By spiit231 in forum C Programming
    Replies: 2
    Last Post: 03-11-2008, 12:25 AM
  2. Dynamic allocation of 2 dim. arrays in classes
    By circuitbreaker in forum C++ Programming
    Replies: 4
    Last Post: 02-10-2008, 12:13 PM
  3. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  4. Find Size Of Dynamic Memory Allocation?
    By appleGuy in forum C++ Programming
    Replies: 7
    Last Post: 06-17-2007, 09:34 AM
  5. Dynamic memory allocation...
    By dicorr in forum C Programming
    Replies: 1
    Last Post: 06-24-2006, 03:59 AM