Search code examples
cmemcpy

memcpy() function usage in C


I have a query about using the memcpy() function.I have written the below program, it compiles but doesn't print an output. The .exe opens and the crashes. I am using Code Blocks as my IDE using GNU GCC compiler.

int main()
{
    char a[]= "This is my test";
    char *b;
    memcpy(b,a,strlen(a)+1);
    printf("After copy =%s\n",b);
    return(0);
}

However, if I change the array *b to b[50] it works!! I don't understand why.

Please provide your suggestions!

Thanks!


Solution

  • Your pointer b is uninitialized. It is pointing to some random location in memory. So when you copy stuff into the memory which b is pointing to, bad things are likely to happen.

    You need to initialize it; perhaps allocate some memory for it with malloc().

    char *b = malloc(strlen(a) + 1);
    

    And then free it when you're finished.

    free(b);