Search code examples
cmemcpy

memcpy crashing after multiple runs


I had written erroneous piece of code, which crashed only after multiple runs in release mode in visual studio (greater than 50). Can someone explain why this piece of code didn't crash much earlier

char *pcBuffer= "Some Text";
char *pctempBuff = NULL;

    pctempBuff = malloc(100);
    memset(pctempBuff,0,100);
    memcpy(pctempBuff,pcBuffer,100);

The above code crashed after multiple runs.

I corrected it to the following code which is correct and it no longer crashes

char *pcBuffer= "Some Text";
char *pctempBuff = NULL;

pctempBuff = malloc(strlen(pcBuffer)+1);
memset(pctempBuff,0,strlen(pcBuffer)+1);
memcpy(pctempBuff,pcBuffer,strlen(pcBuffer)+1);

Solution

  • There are two errors in your initial code.

    malloc can fail, returning NULL in low memory. If you keep allocating memory without freeing any, the system will eventually run out of memory and malloc will return NULL. You need to test for this

    pctempBuff = malloc(100);
    if (pctempBuff != NULL) {
        memset(pctempBuff,0,100);
        memcpy(pctempBuff,pcBuffer,strlen(pcBuffer)+1);
    }
    

    You were also reading memory you didn't own by telling memcpy to copy 100 bytes from the address of the 10 byte pcBuffer. This results in undefined behaviour. A crash after many apparently successful iterations would be a possible (if unlikely) instance of this. Your second example is correct because it only reads the memory for pcBuffer.

    Since you're copying a string, you could do this more clearly/easily/safely by using strcpy

    pctempBuff = malloc(100);
    if (pctempBuff != NULL) {
        strcpy(pctempBuff,pcBuffer);
    }