Problem when copying memory

后端 未结 2 1727
借酒劲吻你
借酒劲吻你 2021-01-29 12:44

So there is a problem I am headbanging over two nights in a row:

(tuple1 and tuple2 are void pointers passed to this function)

char *data;

data = (char*         


        
相关标签:
2条回答
  • 2021-01-29 13:06

    Begin your experiment with something smaller, which is easier to debug:

    void* tuple1 = calloc(2, 1);
    char* content1 = "ab";
    memcpy(tuple1, content1, 2);
    
    void* tuple2 = calloc(4, 1);
    char* content2 = "cdef";;
    memcpy(tuple2, content2, 4);
    
    char *data = data = (char*) calloc (6, 1);
    memcpy(data, tuple1, 2);
    memcpy(data+2, tuple2, 4);
    
    printf("%.*s\n", 6, data); // should print: abcdef
    
    0 讨论(0)
  • I would suspect issues with alignment and/or padding, what are the type declarations of tuple1 and tuple2?

    How do you know their exact sizes? Code that hardcodes things is suspect, there should be some use of sizeof rather than magic number literals.

    Also, you shouldn't cast the return value of calloc(), in C.

    0 讨论(0)
提交回复
热议问题