how do you tell if free works, I was just curious becuase I have no way of telling if free(first) is just wasting a line of code or actually freeing it. I know free returns no value so that doesn't help.
how do you tell if free works, I was just curious becuase I have no way of telling if free(first) is just wasting a line of code or actually freeing it. I know free returns no value so that doesn't help.
Please reply me friend for this code.
Code:#include<stdio.h> #include<conio.h> #include<stdlib.h> main() { char *message; message=(char*)malloc(20);//allocate some memory 20 is just random.......... gets(message);//see to that it should not > 20 printf("\nBefore freeing memory first character is %c\n",*message); free(message); printf("\nAfter freeing the memory first character is %c\n",*message); printf("\n%c\n",*message); }
Saravanan.T.S.
Beginner.
>message=(char*)malloc(20);
The cast isn't needed. You also need to check to see that malloc succeeded.
>gets(message);
gets is *never* needed, use fgets instead.
>printf("\nAfter freeing the memory first character is %c\n",*message);
>printf("\n%c\n",*message);
Bang! You're dead. Accessing memory that you don't own is undefined behavior. When you called free on message, you signed a contract saying that you'll never dereference that pointer again until you point it to memory you own.
>main()
int main ( void ), and remember to return a value at the end.
My best code is written with the delete key.
What prelude told is correct but it is not understood by chrismiceli.
To make it sure what prelude told it did that.
Saravanan.
Saravanan.T.S.
Beginner.
Just clarifying on this point...Accessing memory that you don't own is undefined behavior.
Undefined behavior means it's not guaranteed to work at all. Chances are, that memory you just free()'d won't be messed with if you access it immediately afterwards. But that memory is no longer yours. It could change at any time, without your knowledge. Accessing it could cause a segmentation fault, which crashes your program. Your program could allocate that space back again for some different purpose. That means that two sets of data share memory. This is never a good thing. (Ignore intentional sharing through unions.)
In short, there's no advantage and plenty of disadvantages to doing anything labeled 'undefined behavior'.