Difference between using strcpy() and copying the address of a the char* in C

后端 未结 4 1518
野性不改
野性不改 2020-12-12 02:05

I have two dynamically allocated arrays. c

char **a = (char**)malloc(sizeof(char*) * 5));
char **b = (char**)malloc(sizeof(char*) * 5));

for (int i = 0; i         


        
4条回答
  •  执笔经年
    2020-12-12 02:22

    NO. Both are not same. In this case, strcpy(b[0], a[0]) is correct way to copy the string pointed by a[0] to b[0].

    In case of b[0] = a[0], memory allocated to b[0] will lost and it will cause memory leak. Now freeing both of a[0] and b[0] will invoke undefined behavior. This is because both of them are pointing to same memory location and you are freeing same allocated memory twice.


    NOTE: It should be noted that, as Matt McNabb pointed in his comment, memory leak does not invokes undefined behavior.

提交回复
热议问题