-6
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);

   strcpy(str, "tutorialspoint");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 25);

   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   /* Deallocate allocated memory */
   free(str);

   printf("\n%d",*str);
   return(0);

}
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
Drigy
  • 101
  • 1
  • 8
  • 6
    After `free(str);` dereferencing `str` is _undefined behavior_. – Paul Ogilvie Dec 23 '19 at 15:18
  • 2
    Accessing memory after it was free'd causes undefined behavior, anything might happen. Also, the correct way of printing pointers is with `"%p"` and `(void *)str`. – HolyBlackCat Dec 23 '19 at 15:18
  • 2
    [Please see this discussion on why not to cast the return value of malloc() and family in C..](https://stackoverflow.com/q/605845/2173917) – Sourav Ghosh Dec 23 '19 at 15:21
  • 1
    `str = (char *) realloc(str, 25);` is a very dangerous pattern, should `realloc` fail. – Sourav Ghosh Dec 23 '19 at 15:21
  • I was just trying around code, and noticed this and since I couldn't understand why when I run the program the letter P would always come up, I decided to ask you guys. Thank you. – Drigy Dec 23 '19 at 15:25

1 Answers1

1

Your last print says to print the character pointed to by str as a decimal, which is exactly what it did (for a memory location you just deallocated, making this undefined behavior).

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • 2
    It is UB and could as easily have aborted the program. – Paul Ogilvie Dec 23 '19 at 15:19
  • 1
    "Undefined behavior" means what happens is *undefined*; it just happened to pick the number 80 to display this time. Next time it could be a different number, or a crash. – Scott Hunter Dec 23 '19 at 15:21
  • 2
    @Derteckpt If you are consistently getting the same value, it is could be that your standard library implementation sets free'd memory to a particular value, which happens to be 80 (0x50). If I run it, I consistently get '0'. Either way it is UB and should not be relied upon. – th33lf Dec 23 '19 at 15:27