-1

I am trying to wirte a simple function to move the memory.That sounds like a easy job. However a corruption occur AT LINE 15 when I run the test code in VS 2013 in C language. Thanks a lot for yuor time. :)

Here is source code:

#include <stdio.h>

void* mMemmove(void* dest, const void* src, size_t n)
{
    char* mdest = dest;
    const char* msrc = src;

    if (msrc < mdest)
    {
        msrc += n;
        mdest += n;

        while (n-- != 0)
        {
            *mdest = *msrc;   // where exception occurs !!  
             --mdest;
             --msrc;
             // It was not this function having bug,  but the 
                       //variabe I declare in the main function that cause 
                       //the exception.
        }
    }
    else
    {
        while (n-- != 0)
        {
            *mdest = *msrc;  
            ++mdest;    
            ++msrc;
        }
    }


    return mdest;
}

int main(int argc, const char* argv[])
{
    //char* str1 = "asdfghjkl";
    //char* str2 = "as";                 BUG!
    
    char str1[] = "asdfghjkl";   
    char str2[] = "as";

    mMemmove(str2, str1, 5);
    puts(str1);
    putchar('\n');
    puts(str2);


    return 0;
}


  

the result in VS2013 and win10 shown at the link following

https://i.stack.imgur.com/LIp6h.png

update: why I write this if brach

https://i.stack.imgur.com/Fj5ew.png

Community
  • 1
  • 1
LydonZ
  • 21
  • 4

1 Answers1

0

I think that you are moving to RO memory. Look how you defined str1 and str2 - they point to const char*. Visual studio should give you a warning on those lines.

Try defining a new buffer and moving data to it.

I also don't fully understand that if... what/why?

elcuco
  • 8,948
  • 9
  • 47
  • 69
  • String literals have the type `char []` in C and not `const char []` like in C++ for example, so there should not be a warning for `char* str1 = "asdfghjkl";`. – mch Mar 12 '18 at 11:01
  • Both pointer point to a memory location that is protected and RO. Thats the reason for access violation. – elcuco Mar 12 '18 at 11:13
  • thanks , I rewite the code like this char str1[] = "asdfghjkl"; char str2[] = "as"; And it works! I realize that I made a syntax error. It was not that the function is wrong, but the syntax error I have made. It seems that the VS misguide me to think that I have written the wrong function. Again, thanks a lot. :) – LydonZ Mar 12 '18 at 11:17