Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 < 7, i++) {
  a[i] = (char*)malloc(sizeof(char)*7);
  b[i] = (char*)malloc(sizeof(char)*7);
}

If a[0] was "hello" and I wanted to copy a[0] to b[0], would strcpy and pointer assignment be the same thing? For example:

  1. strcpy(b[0], a[0])
  2. b[0] = a[0]

Would these both do the same exact thing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...