{"id":3833,"date":"2019-11-16T00:01:33","date_gmt":"2019-11-16T08:01:33","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=3833"},"modified":"2019-11-09T11:01:33","modified_gmt":"2019-11-09T19:01:33","slug":"deviously-playing-with-memory","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=3833","title":{"rendered":"Deviously Playing with Memory"},"content":{"rendered":"<p>When a buffer is <em>void<\/em>, its contents are treated as raw memory, not assigned to any specific data type. This ambiguity means your code can cast the memory&#8217;s data type and do interesting things with it.<br \/>\n<!--more--><br \/>\nTo get data into a <em>void<\/em> buffer, use the <em>memcpy()<\/em> function, which was introduced in <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=3831\">last week&#8217;s Lesson<\/a>.<\/p>\n<p>For example, say <code>buffer<\/code> is a <em>void<\/em> pointer: <code>void *buffer<\/code>. The <em>malloc()<\/em> function allocates storage as <em>void<\/em> by default, so you can easily set aside a memory chunk and assign it to buffer easy-peasy:<\/p>\n<p><code>buffer = malloc( sizeof(struct person) );<\/code><\/p>\n<p>To access the contents of <em>void<\/em> <code>buffer<\/code>, however, it&#8217;s best to use a specific data type. For example, create an <em>unsigned char<\/em> pointer <code>bufchar<\/code>. Assign its address to the <em>void<\/em> <code>buffer<\/code> pointer:<\/p>\n<p><code>bufchar = buffer;<\/code><\/p>\n<p>At this point, you can use the <code>bufchar<\/code> pointer to peer into memory, viewing the byte values directly, which is what I&#8217;ve done in the following code:<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n#include &lt;string.h&gt;\r\n\r\nint main()\r\n{\r\n    struct person {\r\n        int age;\r\n        char name[12];\r\n    } man = { 34, \"George\" };\r\n    void *buffer;\r\n    unsigned char *bufchar;\r\n    int x;\r\n\r\n    <span class=\"comments\">\/* output the structure *\/<\/span>\r\n    printf(\"%s is %d years old\\n\",man.name,man.age);\r\n\r\n    <span class=\"comments\">\/* allocate the void buffer *\/<\/span>\r\n    buffer = malloc( sizeof(struct person) );\r\n    if( buffer==NULL )\r\n    {\r\n        fprintf(stderr,\"Unable to allocate memory\\n\");\r\n        exit(1);\r\n    }\r\n\r\n    <span class=\"comments\">\/* copy memory *\/<\/span>\r\n    memcpy(buffer,&amp;man,sizeof(struct person));\r\n    \r\n    <span class=\"comments\">\/* dump the buffer *\/<\/span>\r\n    puts(\"Buffer dump:\");\r\n        <span class=\"comments\">\/* reference (void)buffer as (char)bufchar *\/<\/span>\r\n    bufchar = buffer;\r\n    for( x=0; x&lt;(int)sizeof(struct person); x++ )\r\n    {\r\n        printf(\" %02X\",*(bufchar+x));\r\n    }\r\n    putchar('\\n');\r\n\r\n    return(0);\r\n}<\/pre>\n<p>The <em>person<\/em> structure <code>man<\/code> is copied into the <em>void<\/em> <code>buffer<\/code> at Line 27. At Line 32, <em>unsigned char<\/em> pointer <code>bufchar<\/code> is assigned the same address as <code>buffer<\/code>. The contents of <code>buffer<\/code> are then dumped as <em>unsigned char<\/em> hexadecimal digits, effectively peering into <code>buffer<\/code> at a raw-byte level. Here&#8217;s the output:<\/p>\n<p><code>George is 34 years old<br \/>\nBuffer dump:<br \/>\n&nbsp;22 00 00 00 47 65 6F 72 67 65 00 00 00 00 00 00<\/code><\/p>\n<p>The <code>buffer<\/code> consists of two members: The first four bytes are the integer member <em>age<\/em>, the next 12 bytes store the <em>name<\/em> string, &#8220;George,&#8221; which occupies only the first seven bytes of this storage. This allocation is illustrated in Figure 1.<\/p>\n<div id=\"attachment_3849\" style=\"width: 501px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-3849\" src=\"https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2019\/11\/1116-figure1-1.png\" alt=\"\" width=\"491\" height=\"120\" class=\"size-full wp-image-3849\" srcset=\"https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2019\/11\/1116-figure1-1.png 491w, https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2019\/11\/1116-figure1-1-300x73.png 300w\" sizes=\"auto, (max-width: 491px) 100vw, 491px\" \/><p id=\"caption-attachment-3849\" class=\"wp-caption-text\">Figure 1. Memory allocation for the <em>person<\/em> structure variable <code>man<\/code>, shown as <em>unsigned char<\/em> hex values.<\/p><\/div>\n<p>Because the data types and their offsets within the <em>void<\/em> <code>buffer<\/code> are known, you can access them directly. To access the integer portion, an <em>int<\/em> pointer <code>bufint<\/code> can be used. This pointer would be initialized to the start of <code>buffer<\/code>, which is where the integer value dwells:<\/p>\n<p><code>bufint = (int)buffer;<\/code><\/p>\n<p>You can re-use the <code>bufchar<\/code> pointer to access the string. Its location is at offset 4 (the fifth byte) in <code>buffer<\/code>:<\/p>\n<p><code>bufchar = (char *)buffer+4;<\/code><\/p>\n<p>The final part of this code update shows the modifications:<\/p>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n#include &lt;string.h&gt;\r\n\r\nint main()\r\n{\r\n    struct person {\r\n        int age;\r\n        char name[12];\r\n    } man = { 34, \"George\" };\r\n    void *buffer;\r\n    int *bufint;\r\n    char *bufchar;\r\n    int x;\r\n\r\n    <span class=\"comments\">\/* output the structure *\/<\/span>\r\n    printf(\"%s is %d years old\\n\",man.name,man.age);\r\n\r\n    <span class=\"comments\">\/* allocate the void buffer *\/<\/span>\r\n    buffer = malloc( sizeof(struct person) );\r\n    if( buffer==NULL )\r\n    {\r\n        fprintf(stderr,\"Unable to allocate memory\\n\");\r\n        exit(1);\r\n    }\r\n\r\n    <span class=\"comments\">\/* copy memory *\/<\/span>\r\n    memcpy(buffer,&amp;man,sizeof(struct person));\r\n    \r\n    <span class=\"comments\">\/* dump the buffer *\/<\/span>\r\n    puts(\"Buffer dump:\");\r\n        <span class=\"comments\">\/* reference (void)buffer as (char)bufchar *\/<\/span>\r\n    bufchar = buffer;\r\n    for( x=0; x&lt;(int)sizeof(struct person); x++ )\r\n    {\r\n        printf(\" %02X\",*(bufchar+x));\r\n    }\r\n    putchar('\\n');\r\n\r\n    <span class=\"comments\">\/* sneak into the buffer *\/<\/span>\r\n        <span class=\"comments\">\/* reference (void)buffer as (int)bufint *\/<\/span>\r\n    bufint = (int *)buffer;\r\n        <span class=\"comments\">\/* reference (void)buffer (offset 4) as (char)bufchar *\/<\/span>\r\n    bufchar = (char *)buffer+4;\r\n        <span class=\"comments\">\/* data can now be accessed directly *\/<\/span>\r\n    printf(\"Int portion: %d\\n\",*(bufint));\r\n    printf(\"String portion: %s\\n\",bufchar);\r\n\r\n    return(0);\r\n}<\/pre>\n<p>And here&#8217;s the output:<\/p>\n<p><code>George is 34 years old<br \/>\nBuffer dump:<br \/>\n&nbsp;22 00 00 00 47 65 6F 72 67 65 00 00 00 00 00 00<br \/>\nInt portion: 34<br \/>\nString portion: George<\/code><\/p>\n<p>Because the <em>memcpy()<\/em> function duplicates the structure into a <em>void<\/em> buffer, other pointers of specific data types can access the <em>void<\/em> data, interpreting it accordingly.<\/p>\n<p>This type of memory manipulation isn&#8217;t without risk: Accessing unknown (<em>void<\/em>) buffers with any old data type can lead to unpredictable results. Ensure that you know the data you&#8217;re accessing and, should you want to manipulate it, that your actions result in safe and secure coding practices.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Using the <em>memcpy()<\/em> function and playing with pointer data types allows you to examine raw memory in your code. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=3833\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-3833","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/3833","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3833"}],"version-history":[{"count":8,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/3833\/revisions"}],"predecessor-version":[{"id":3859,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/3833\/revisions\/3859"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3833"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3833"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3833"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}