Open side-bar Menu
 Embedded Software
Colin Walls
Colin Walls
Colin Walls has over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, Colin is an embedded software technologist with Mentor … More »

Problems with pointers: out of scope, out of mind

 
December 16th, 2019 by Colin Walls

There is sometimes a little confusion about the difference between the scope of a variable/object and its actual existence. For “existence”, read “validity” because the memory occupied by a variable never goes away; the time at which the memory is actually allocated to the variable varies …

I will illustrate this point with some C code.

int *fun()
{
   int arr[10];
   ...
   return arr;
}

void f2()
{
   int *p;
   p = fun();
   p[3] = 99;
}

In this code, the array arr has a scope which is limited to inside the function fun(). The memory it uses is also allocated at the start of this function and deallocated when the code returns. However, this code, though syntactically correct, has a glaring error: it returns a pointer to arr so that the code in function f2() can access the array after the return from fun(). But, since this memory has now been deallocated, the assignment to p[3] is not valid and could produce an “interesting” error. Remember that pointers, though a powerful language feature in C/C++, are the most common source of errors.

A small change to the code rectifies this fault.

int *fun()
{
static int arr[10];
...
return arr;
}

void f2()
{
int *p;
p = fun();
p[3] = 99;
}

By declaring arr to be static the time frame of its existence is changed. The memory is now allocated at build time so it is in existence before, during and, most importantly, after the execution of fun() so the assignment to p[3] is now valid. The scope of arr is unchanged: it is only accessible inside fun().

Logged in as . Log out »




© 2024 Internet Business Systems, Inc.
670 Aberdeen Way, Milpitas, CA 95035
+1 (408) 882-6554 — Contact Us, or visit our other sites:
TechJobsCafe - Technical Jobs and Resumes EDACafe - Electronic Design Automation GISCafe - Geographical Information Services  MCADCafe - Mechanical Design and Engineering ShareCG - Share Computer Graphic (CG) Animation, 3D Art and 3D Models
  Privacy PolicyAdvertise