Without malloc, it looked like you did not initialise the pointer at all. As such, your attempt to print the value of *p resulted in undefined behaviour.
For the sizeof results: think about what you already know of sizeof. If you know nothing, then it is time to do some research.
By the way, remember to use free() after you are done with what you allocated with malloc().
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
without malloc:
----------------
madhu@Ideapad:~/Desktop$ ./a.out
-1217282060 // char *p is not pointing to anything so garbage is printing
124 // not sure about this output
4 // sizeof charater pointer is 4 bytes
1 // size of a charater is 1 byte
4 // same as size of charater pointer: 4 bytes
With malloc:
---------------
madhu@Ideapad:~/Desktop$ ./a.out
138657800 // char *p is not pointing to anything so garbage is printing
0 // not sure about this output
4 // sizeof charater pointer is 4 bytes
1 // size of a charater is 1 bytes
4 // same as size of charater pointer: 4 bytes
is it correct?
can you explain the second one, why it is printing 124 and 0 ?
I already told you that dereferencing that pointer results in undefined behaviour. The output you get here is presumably whatever was at the "garbage" memory location, or it could be something else since no output was even required to begin with.
Originally Posted by madhu542
138657800 // char *p is not pointing to anything so garbage is printing
This is wrong: the pointer p does point to something since it was assigned the return value of malloc.
Originally Posted by madhu542
0 // not sure about this output
This just means that the first byte of the memory allocated by the use of malloc happened to contain a 0. It could have legitimately been some other value instead.
Other than these, yes, your observations appear correct to me.
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
without malloc:
----------------
madhu@Ideapad:~/Desktop$ ./a.out
-1217282060 // char *p is not pointing to anything so garbage is printing
For this line:
Code:
printf("%d\n", *p);
Your answer here is wrong if malloc() is not called. There is no guarantee that the program even works when that line is executed. When you dereference an uninitialized pointer, as laserlight stated, the program's behaviour is undefined. The program could blow up as soon as that line is executed.
(I know of one OS where this can happen, and that is the 16-bit MSDOS OS, where dereferencing uninitialized pointers would sometimes cause reboots of the PC to occur).
Bookmarks