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

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...