-1

I'm trying to setup a pointer function that returns the adress of the first element of an array which is stored locally in itself, and then use (in this case print) the contents on another function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <stdbool.h>

double *n(int a)
{

   int i;
   double array[' '];

   for(i=0;i<a;i++) 
      {

       array[i] = rand();
       printf("\n element: %f \t\n\n", array[i]);
    
      }

    return array;

}

void exe()
{

    double *unfixed;
    int c, b, j;

    
    scanf("%d", &b);
    unfixed = n(b);

    printf("\n\n Precoded acces value %f \n\n", *(unfixed + c));

    for(j=0;j<b;j++)
    {
        printf("\n %f", *(unfixed + j));
    } 

    return;
}

int main()
{

    exe();

    return 0;

}

It works properly when I refer to it by static statements, example:

printf("\n\n %f \n\n", *(unfixed + c));

On the contrary when I go ahead and try to get a cycle or decision to be made it just straight up doesn't work.

P.D.: Also for some unholy reason it works perfectly with int type pointer functions.

Further evidence of the psychological abuse

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    One of the possibilities of undefined behavior is that it appears to work, sometimes. Returning a pointer to a local is the biggest problem, but I wonder if you know what `double array[' '];` is actually declaring. What if `a` is larger than 32? – Retired Ninja Oct 02 '21 at 08:24
  • 2
    `double array[' '];` is a very interesting way of declaring an array with 32 elements. If you need 64 entries, just switch to `double array['@'];`. – glglgl Oct 02 '21 at 08:32
  • You **can't return a pointer to a local variable** because it will be destroyed on function exit. Use `malloc` instead to allocate the `array[' ']` of doubles. And avoid to use obscure constructs as `'[' ']` to allocate a 32 elements array. Last check for aout of bounds access. – Frankie_C Oct 02 '21 at 08:34

1 Answers1

1

The function n returns a pointer to the first element of a local array with automatic storage duration that will not be alive after exiting the function. So the returned pointer is invalid. Dereferencing such a pointer invokes undefined behavior.

You could declare the array as having static storage duration

static double array[' '];

or allocate the array dynamically.

But in any case the function is unsafe because there is no check whether a is not greater than the value of the integer character literal ' ' used as the size of the array.

Also within the function exe you are using the variable c that was not initialized in this statement

printf("\n\n Precoded acces value %f \n\n", *(unfixed + c));

that again invokes undefined behavior.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335