'dynamic data to read only in C

how can I pass the value of a dynamic-allocated variable to a read-only one and right just after free the dynamic one.

Say I've got a function to create a string with any length I want and then call it in a the main one you see bellow to print the string the function generated but then I forgot to free or maybe I don't want to free it as a I'd expect somehow it's been already freed within the function

   1 ~ │ #include <stdio.h>
   2 ~ │ #include <stdlib.h>
   3 ~ │ #include <string.h>
   4 ~ │ 
   5 ~ │ char *CreateTxt();
   6 ~ │ 
   7 ~ │ int main() {
   8 ~ │    char *str = CreateTxt();
   9 ~ │    printf(("%s\n"), str);
  10 ~ │ }
  11 ~ │ 
  12 ~ │ char *CreateTxt() {
  13 ~ │    char *p_dynamicTxt = calloc(5, sizeof(char));
  14 ~ │    strcpy(p_dynamicTxt, "A");
  15 ~ │    char *string = p_dynamicTxt;
  16 ~ │    free(p_dynamicTxt); // Want to free here instead of after calling
  17 ~ │    return string;
  18 ~ │ }

I want to be able to free the variable allocated with calloc within the function so other people that may use the function don't gotta worry about freeing the return value

Obviously when I compile and run I get this

-- Configuring done
-- Generating done
-- Build files have been written to: /home/prxvvy/workspace/a/cmake-build-debug
[2/2] Linking C executable a
«øo]
^[[?1;2c%     
c


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source