Yes. Absolutely, you are right about local data goes out of scope, but the value is always correct since the pointer is going out of scope, but the memory, which pointer pointed to is still there unless you explicitly delete pointer, then that memory location will contain garbage.
No. Undefined behavior is, well, undefined behavior.
Let's say you have an array local to a function. This data is created on the stack. You call this function and return a pointer to the first element of it -- you are pointing somewhere on the stack.
Then you call another function that also has local variables. This function also uses the stack, and it tramples your data. And the pointer returned by the first function is still pointing to the same place.
This is just one possible example of your assertion being incorrect. So "always correct" is not true.
[edit]Since you can't return an array, this is the closest simulation I could devise.
#include <stdio.h>
int *getGraph(void)
{
int init[6][6] =
{
{ 0, 5, 10, -1, -1, -1},
{-1, 0, -1, 2, -1, -1},
{-1, -1, 0, -1, 10, -1},
{-1, -1, -1, 0, 1, -1},
{-1, -1, -1, -1, 0, 10},
{-1, -1, -1, -1, -1, 0},
};
int i, j;
puts("getGraph:");
for (i = 0; i < 6; ++i)
{
for (j = 0; j < 6; ++j)
{
printf("%2d ", init[i][j]);
}
putchar('\n');
}
return init;
}
void printGraph(const int g[6][6])
{
int i, j;
puts("printGraph:");
for (i = 0; i < 6; ++i)
{
for (j = 0; j < 6; ++j)
{
printf("%2d ", g[i][j]);
}
putchar('\n');
}
}
int main(void)
{
int (*graph)[6] = getGraph();
printGraph(graph);
return 0;
}
/* my output
getGraph:
0 5 10 -1 -1 -1
-1 0 -1 2 -1 -1
-1 -1 0 -1 10 -1
-1 -1 -1 0 1 -1
-1 -1 -1 -1 0 10
-1 -1 -1 -1 -1 0
printGraph:
0 5 10 -1 -1 -1
-1 0 -1 2 -1 4223327
-1 1245004 10 1244919 4223327 4223339
0 11 -1 -1 1245028 4209022
4208532 4224044 4223339 1245044 1245056 4198704
4223339 4223339 0 4223088 0 1245068
*/