why this code is showing double free corruption?Code:int main() { int *a,i; a=(int *)malloc(10*sizeof(int)); for(i=0;i<10;i++) *(a+i)=i*i; for(i=0;i<10;i++) printf("%d",*a++); free(a); return 0; }
why this code is showing double free corruption?Code:int main() { int *a,i; a=(int *)malloc(10*sizeof(int)); for(i=0;i<10;i++) *(a+i)=i*i; for(i=0;i<10;i++) printf("%d",*a++); free(a); return 0; }
It may not be a double free per se, but you are incrementing a. Rather, have another pointer to be a copy of a, and increment that. That way, free(a) will operate on the original location pointed to by a.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
This smells like a test question.
What is a? What is its value prior to the final loop? What about after? How can that affect the free operation?
Thanks laser
I have used a+i in place of a++ it fine now.
But another doubt
How this code is giving 16?Code:main() { double d; printf("%d", ((double *)0+2)); }
Because %d does NOT print doubles.
r2r is right, you're just trotting off quiz questions.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
He's printing a pointer value there. 16 would be the expected offset from NULL.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
3. Get rid of conio.h and other antiquated DOS crap headers.
4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.