It may work fine, but it is not very safe. By writing data outside the allocated memory block, you are overwriting some data that should not be. This is one of the biggest causes of segfaults and other memory errors, and what you observe with it working in this short program makes it difficult to find the root cause.
Read this article , in particular the memory corruption part, to begin to understand the problem.
Valgrind is a great tool for analyzing memory errors, such as the one you provide.
@ David made a good comment. Compare the results of your code execution with the following code , Note that the latter leads to a runtime error (with practically no useful output!) On ideone.com (click on the links), while the former succeeds as you survived.
main() { int *p; p=malloc(sizeof(int)); printf("size of p=%d\n",sizeof(p)); p[500]=999999; printf("p[0]=%d",p[500]); p[500000]=42; printf("p[0]=%d",p[500000]); return 0; }
marcog
source share