Thread: Overlapping Memory

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    13

    Overlapping Memory

    Hi

    I have to create a test case where one object is copied to the other when both of the objects have some overlapping memory.

    I have experimented with memmove and memcpy and the use of unions.

    I am not sure how to use memmove successfully using union members.

    at the momemet i have

    Code:
    #include <string.h>
    
    typedef float float32_t;
    typedef int int32_t;
    typedef char char_t;
    
    
    char_t main(int32_t a)
    {
    char_t Buffer[]= "is this a violation?";
         
    union aUnion /*Violation of Rule 18.2 and 18.4*/
    {
          int32_t x;
          float32_t y;
    };
    
    union aUnion test; /*Violation of 18.4*/
    
    test.x=1;
    test.y=5.0f;
    
    memcpy(&Buffer[5], &Buffer[10], 10U); /*Possible Violation*/
     
    a=test.x+a;/*Violation value of test.x undefined, x has been overlapped*/
    
    return(Buffer[5]);
    }
    Memmove above overlaps teh memory of one bject but i require two separate objects to be overlapped!

    IS there a way I can use the union members in memcpy and have it compile????


    Thanks

    Hamish

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Either I'm not understanding, or your question is incredibly unclear.

    The way to copy arrays if there is a potential overlap of source and destination is to use memmove.

    The significance of your union type in this is as clear as mud to me. The whole point of unions is that the members occupy the same memory. In your example, in which test is of type aUnion, then test.x and test.y occupy the same memory (ie. (void *)(&test.x) == (void *)(&test.y)), where the void * casts are to ensure we're comparing pointers of the same type.

    One characteristic of unions is that (using your aUnion type to demonstrate) if you modify test.y, then the value of test.x changes (but the result is implementation defined). In other words if you modify test.y, there is no means of retrieving the original value of test.x as test.y and test.x occupy the same memory.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. available memory from task manager
    By George2 in forum Tech Board
    Replies: 10
    Last Post: 01-18-2008, 02:32 AM
  2. Replies: 4
    Last Post: 01-13-2008, 02:14 AM
  3. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  4. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  5. Shared Memory - shmget questions
    By hendler in forum C Programming
    Replies: 1
    Last Post: 11-29-2005, 02:15 AM