Reputation: 1463
In my visual studio, this code
int *a, *b;
b = a;
a = (int *)malloc(SIZE * sizeof(int));
Will receive a run-time check failure:variable being used without being initialized. So if a pointer is not allocated memory then the assignment is nonsense and forbidden? In my old opinion, a pointer is a 4 byte number in my development environment to describe a address. So in imagination,it is this:
int *a, *b;
b = a;
a = (int *)malloc(SIZE * sizeof(int));
*a = 10;
printf("%d", *b);
Then *b = 10; But apparently it is not that way... So my confused is the why pointer a and b doesn't point to the same memory in the way below? Can somebody explain this to me ?
Upvotes: 0
Views: 2323
Reputation: 530
For detailed explanation,
malloc() allocates size bytes and returns a pointer to the allocated memory. So pointer will get new memory address assigned after successful malloc, because of which after malloc call address of a & b differs which on de-reference gives different values.
If you see output of below program, you will get your answer.
#include<stdio.h>
#include<stdlib.h>
#define SIZE 1
main()
{
int *a, *b;
b = a;
printf("Address of a:%p\n", a);
printf("Address of b%p\n", b);
a = (int *)malloc(SIZE * sizeof(int));
printf("Address of a:%p\n", a);
printf("Address of b%p\n", b);
b = a; //assigning address of a to b
*a = 10;
printf("%d\n", *b);
}
Output:
Address of a: 0x7fff2f2813c0
Address of b: 0x7fff2f2813c0
After allocating memory to pointer 'a',
Address of a: 0x1829010
Address of b: 0x7fff2f2813c0
10
Upvotes: 0
Reputation: 50
As you've seen an example from @Matt McNabb this
int*a, *b;
b = a;
doesn't mean where ever "a" is pointing, be will always point to that location after this assignment. It will do the trick only the first assignment ie.
int *a, *b;
int k = 10;
int m = 20;
a = &k;
b = a; // this will point b to k
a = &m; // this will change a to point to m however b will remains pointing to k
Also, please note as @Barry said, you firstly have uninitialized pointer, then you assign b to point to the place where that uninitialized pointer is pointing to << this is a really bad programming habit as you will never know where a was firstly pointing to (I'm not sure if it depends on machine and compiler or not). It could cause you a big mess.
Upvotes: 1
Reputation: 303517
This is bad:
int *a, *b;
b = a;
for the same reason that this is bad:
int a, b;
b = a;
You are reading an uninitialized variable. a
has indeterminate value. It doesn't actually have to point to allocated memory, this would be fine:
int* a = 0;
int* b = a; // OK, a was initialized
Upvotes: 4