int ** foo(int row)
{
     int *arr[100];

     for(int i=0;i<10;i++)
     {
           arr[i]=malloc(sizeof(int)*10);
     }

     int **p=(int**)arr;

     return p;
}

what is the problem with this code snippet ? it is not a homework. it is my interview question.

parameter row is unused.

The function returns a pointer to an object, arr, that is on the stack and that will therefore be deleted once the function exits which is almost certainly likely to produce undefined behaviour.

Line 10 and 12 are equivilent to return arr;

wow.... 101% same statement by me.... awesome.... :-) exactly same... actually, he gave a big smile after this. so i thought it is wrong that why he is smiling. :p yoo!! and these concepts are only because of daniweb. no issues.

You are returning a reference to a local variable - not good! Even though the elements of arr[] are allocated on the heap (malloc()), arr[] itself is not. This would work if you made it static, but the fact of the matter is that this is REALLY bad code! Rethink your approach.

There are actually a number of problems with that function, though returning a pointer to a local variable is probably what the interviewer wanted.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.