Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "point" mean here?

Tags:

c

At some memory allocation I find this. But I don't understand it.

char * mem_alloc()
{   
    char *point;
    char *a;
    point = (char *)malloc(block_num);

    a = *(char**) point;
    return a;
}   
like image 357
chen youfu Avatar asked Feb 21 '23 05:02

chen youfu


1 Answers

char * mem_alloc()

In my experience, functions returning a pointer are almost always a sign of flawed program design. Such a pointer could point at the following:

  • a local variable (blatant bug, UB)
  • a global/static (poor program design and also not thread-safe)
  • dynamic memory (poor program design, the code using the memory should handle the allocation, great potential for leaks)
  • or to one of the parameters passed to the function (poor program design, obscure function interface)

In this case, it points to dynamic memory, so we can likely assume poor program design and likely memory leaks to go with it.

point = (char *)malloc(block_num);

This code means that whoever wrote it is confused over how malloc works and how void pointers work. The result of malloc should never be typecasted, see this and this. The urge to typecast means that the programmer is confused about the C language, and/or that they are trying to compile C code on a C++ compiler.

"block_num" is suspicious, if this is a global, non-constant variable, then the program design is poor.

a = *(char**) point;

This means, take the address of point, which is pointing at uninitialized memory on the heap, then pretend that point is a pointer-to-pointer and thereby treat the garbage contents of the heap as if it was a pointer. Then return this pointer, pointing out at a random location in in la-la land, to the caller. And while doing so, create a memory leak.

like image 177
Lundin Avatar answered Mar 05 '23 10:03

Lundin