0

if I have a C function where I return a pointer to a malloc-ated memory location like -->

int *example0{
    int *ptr;
    ptr = malloc(10);
    ptr[0] = '1';
    return ptr;
}

call that function twice and at the first function call do not free() the ptr

int example2{
    int *exmple = example0();
}

int example3{
    int *exmple2 = example0();
    free(exmple2);
}

does C run the compiled example0 function twice or does C only return the ptr to the not free()-ed pre "filled" memory-location at the second function call?

If: C does run the function twice, how can I not waste computing time at running the function twice?

majortobi
  • 3
  • 3
  • Please fix the syntax in your question. It's currently not valid C. – AKX May 14 '21 at 09:09
  • Your functions doesn't actually do any thing, so discussing how to rewrite it doesn't really make any sense without more context. If you want to avoid a `malloc` in a function, one way is to let the caller pass a pointer to buffer. – HAL9000 May 14 '21 at 14:03

1 Answers1

0

does C run the compiled example0 function twice or does C only return the ptr to the not free()-ed pre "filled" memory-location at the second function call?

If you call the function twice, your program calls the function twice, and you also mallocate memory twice. It doesn't know about the other time you called the function.

If: C does run the function twice, how can I not waste computing time at running the function twice?

Don't call the function twice? Alternately, if what you really do want is the buffer to be only allocated once, you can make it a static variable.

AKX
  • 152,115
  • 15
  • 115
  • 172
  • 1
    static variables are usually a bad idea as it makes function non-reentrant which is a problem in the multitasking environment. BTW in this case, `static` does not change anything as `malloc` will be called twice anyway causing the memory leak. – 0___________ May 14 '21 at 09:51
  • @0___________ Yes, global state (which include static variables) can be a bad idea. As for the BTW, yup - OP will of course need to do other changes than just declare the variable static. – AKX May 14 '21 at 09:53
  • then you should show him what to do to avoid multiple `malloc`s I do not think that he is able to do so (judging from the question) – 0___________ May 14 '21 at 10:16