简体   繁体   中英

can two char * have the same memory address even with malloc?

I understand that if I have the following:

char* c1 = "apple";
char* c2 = "apple";

Then these two char* can have exactly the same memory address. But what if I have the following:

char* c1 = (char*)malloc(sizeof(char)*10);
memset(c1, 0, 10);
c1[0]='a';c1[0]='p';c1[0]='p';c1[0]='l';c1[0]='e';
char* c2 = (char*)malloc(sizeof(char)*10);
memset(c1, 0, 10);
c2[0]='a';c2[0]='p';c2[0]='p';c2[0]='l';c2[0]='e';

Is it possible that c1 and c2 have the same address even in this case?

Actually in the first situation where c1 and c2 are both pointers to string literals:

char* c1 = "apple";
char* c2 = "apple";

whether c1 and c2 have the same value is unspecified. In another word, they may, or may not have the same address.


In the second situation, the only possibility that c1 and c2 have the same value is when both calls to malloc failed, in which case they are both null pointers. Otherwise, they will have different values.

That's the reason that you should check the return value of malloc .

malloc will return unique addresses or NULL for c1 and c2 , so the values will be different unless malloc fails for both. Besides the NULL case, there's no way for malloc to magically return the same address for things that will become the same value.

However, you could certainly have said:

c2 = c1;

and c2 would refer to the same spot in memory as c1 .

Is it possible that c1 and c2 have the same address even in this case?

No.

malloc() allocates block of memory on each call.

you have called malloc() consecutively those two addresses are different.

No. Not possible*. Whenever memory is allocated, it is taken out of a "free" list of memory. Then any subsequent calls to malloc can only reserve memory from the "free" list.

But when you put

char *c1 = "apple"

"apple" is put in a static part of the memory reserved for the entire process.
After which, it depends upon the compiler whether it wants to give the same memory address for "apple" to char *c2 or not.

* It should not happen, and is wrong. But speaking out of context of standard C/C++ and possibly for some other programming language, nothing is stopping a compiler(which is a program like any other) to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM