Home > Enterprise >  dynamic data to read only in C
dynamic data to read only in C

Time:03-01

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%     

CodePudding user response:

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

You can't. The lifetime of an allocated object ends when it is freed. Undefined behavior results from attempting to access an object outside of its lifetime.

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

It's nice that you want to make things easy for your users, but what you propose is not among the ways available to you to do that. The best available thing to do is clearly document any requirements that attend calling the function, such as to free the data pointed to by the function's return value. It is then the caller's responsibility to use the function according to its documentation.

  •  Tags:  
  • c
  • Related