0

my question is simple, the code shows the problem:

this works

   char *str1;
   str1 = (char *) malloc(3);
   strcpy(str1, "hi"); 
   printf("%s\n", str1);

   str1 = realloc(str1, 5); 
   strcpy(str1, "hi ho");
   printf("%s\n", str1);

this not, why?

   char *str2;
   str2 = (char *) malloc(3);
   str2 = "hi";            // not using strcpy
   printf("%s\n", str2);

   str2 = realloc(str2, 5); 
   str2 = "hi ho";         // not using strcpy
   printf("%s\n", str2);

terminal output:

hi
hi ho
hi
realloc(): invalid pointer

edit: so is the Segmentation fault in this programm the same type of error?

int main() {
   char * s_test = malloc(3);
   s_test = "ho";
   printf("s: %s", s_test);
   // should we free now ? 
   free(s_test); // segmentation fault core dumped
   return 0;
}
Jonas Frey
  • 65
  • 6
  • 3
    `str2 = "hi";` doesn't do what you think it does.. – ikegami Jan 27 '22 at 16:03
  • wow , what a short and precise answer-.- ... – Jonas Frey Jan 27 '22 at 16:19
  • 1
    The `malloc` assignment makes `str2` point to some dynamically allocated memory. The `str2 = "hi";` makes it point to a read-only section containing that hard-coded string. The reference to the dynamically allocated memory is "lost" and is never freed. The `realloc` call is invalid because the hard-coded "hi" string was never dynamically allocated. – Cheatah Jan 27 '22 at 16:35

0 Answers0