Hi

GCC does warn if returning a pointer to a local variable (stack memory).
But there are alot of more cases where GCC could possibly warn,
eg. when references are made to local variables or stack memory.

See this attached example code.
GCC warns for first case, but not the others.
I think all cases can be considered program bugs,
and could trigger a compiler warning I think.

I've found out that the present warning is done in "c-typeck.c",
is this the right place to but additional warnings of this kind too?

Thanks & Best Regards
Fredrik Hederstierna

The example code file
Compiled with "-O2 -W -Wall -Wextra"
---------------------------

#include <stdio.h>
#include <stdlib.h>

int * test_ptr;

struct test {
  int *ptr;
};

int* test_return_ptr_to_stack_mem(void)
{
  int a[100];
  // CORRECT WARNING:
  // "warning: function returns address of local variable".
  // (Checking done in file gcc/c-typeck.c, function c_finish_return()).
  return a;
}

void test_set_ptr_to_stack_mem(void)
{
  int a[100];
  // GIVE WARNING?
  // "function returns with external reference to local variable?"
  test_ptr = a;
  return;
}

void* test_alloc_struct_ptr_to_stack_mem(void)
{
  int a[100];
  struct test* t = (struct test*)malloc(sizeof(struct test));
  // GIVE WARNING?
  // "function returns with reference to local variable?"
  t->ptr = a;
  return t;
}

void* test_alloc_struct_on_stack_mem(void)
{
  struct test* t = (struct test*)alloca(sizeof(struct test));
  t->ptr = NULL;
  // GIVE WARNING?
  // "function returns allocation from stack memory?"
  return t;
}

int main(void)
{
  // GIVES WARNING
  int* t1 = test_return_ptr_to_stack_mem();
  printf("Stack mem ref test 1: %p\n", t1);

  // NO WARNING?
  test_set_ptr_to_stack_mem();
  printf("Stack mem ref test 2: %d\n", test_ptr[0]);

  // NO WARNING?
  struct test * t3 = test_alloc_struct_ptr_to_stack_mem();
  printf("Stack mem ref test 3: %d\n", t3->ptr[0]);

  // NO WARNING?
  struct test * t4 = test_alloc_struct_on_stack_mem();
  printf("Stack mem ref test 4: %p\n", t4->ptr);

  return 0;
}

Reply via email to