Reputation: 1545
While writing my code I came upon a problem
char* a = malloc (sizeof(char));
a = "blabla";
free(a);
gives me an error, because I changed the value of the pointer a to something else.
So, why does this work
char* a = "blabla";
printf("%s", a);
again I'm changing the value of the pointer to blabla
, I'm ruining the pointers address. It should be error, shouldn't it?
Upvotes: 4
Views: 164
Reputation: 2115
In the second one you are creating a pointer to the string literal "blabla"
, it doesn't affect the pointer in any way, a new pointer is created. In the first example you change the value of the pointer itself.
Upvotes: 2
Reputation: 21
The first snippet where your address gets lost where 'blaba' is stored It will give error.In the second one you assinged directly the value to blabla
Upvotes: -1
Reputation: 106012
The first snippet causes memory leak. Once the statement a = "blabla";
is executed, the pointer a
will no longer point to the memory allocated by malloc
and its address gets lost.
Upvotes: 1
Reputation: 182753
The first case has a bug because you are passing an address to free
other than one you got from malloc
. That is an error.
The second case has no such problem, so why shouldn't it work? You aren't "ruining" the pointer's address, you are setting it to a valid address and then using that valid address for a valid purpose.
The second example is no different from:
int i = 1;
printf ("%d", i);
You set its value and used the new legal value in a proper way, so no problem.
Upvotes: 4