Do pointers from malloc point to the same memory address or unique addresses?

0
0
Asked By TechieGiraffe29 On

I'm trying to understand how pointers work in C, specifically when using malloc. I declared two pointers like this:

`struct cplx *p1 = malloc(sizeof(struct cplx));`
`struct cplx *p2 = malloc(sizeof(struct cplx));`

My question is, do p1 and p2 point to the same address, meaning they can modify each other's values, or do they point to separate copies of the struct cplx? Thanks, and I'd appreciate short replies!

2 Answers

Answered By CodeWizard77 On

When you call `malloc()`, it allocates unique memory for each pointer. So, p1 and p2 will point to different memory addresses, meaning they can modify their own values independently without affecting each other.

Answered By LogicalLlama34 On

Just to clarify, in this example:
`struct cplx *p1 = malloc(sizeof(struct cplx));`
`free(p1);`
`struct cplx *p2 = malloc(sizeof(struct cplx));`
In this case, p1 and p2 could indeed point to the same memory location after p1 is freed, but that behavior is not guaranteed. It's best practice to consider every `malloc()` call as giving you a unique block of memory.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.