0

I have been using ODBC in C. They have a defined type:

typedef void *          SQLPOINTER;
typedef unsigned int    SQLUINTEGER;

I have a function alloc_buffer:

void db_alloc_buffer(SQLUINTEGER buffSize, SQLPOINTER *Ptr)
{
    *Ptr = malloc(buffSize);
    memset(*Ptr, ' ', buffSize); 
}

Is is safe/correct to de reference Ptr? or can I do:

void db_alloc_buffer(SQLUINTEGER buffSize, SQLPOINTER *Ptr)
{
    Ptr = malloc(buffSize);
    memset(Ptr, ' ', buffSize); 
}
TheGreatNes
  • 73
  • 1
  • 9

2 Answers2

0

No, it's not safe to dereference Ptr the way you are in the second version. Ptr is a pointer to a pointer, not a pointer directly to the buffer. The purpose of this function is to allocate a buffer that can be used by the caller. The caller provides the address of their pointer variable, and your function is supposed to allocate a buffer and set that variable to the address of the buffer, and it does that by dereferencing Ptr with the result of malloc().

If you assign to Ptr instead of *Ptr, that just assigns to the local variable, not the caller's variable.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

can a void * be malloced?

Yes. Why couldn't it: void** p = malloc(sizeof(void*));

Is is safe/correct to de reference Ptr?

Safe? Only if Ptr points to valid memory. If someone calls db_alloc_buffer(n, NULL) then it definitely isn't safe.

Correct? That depends on what you're trying to do. The second code doesn't seem useful because you're ignoring the value of the argument that was passed in as Ptr.

The first version seems more useful, since it at least has some observable effects outside the function, namely that it modifies the SQLPOINTER that was passed as Ptr.

It seems that you want something like this:

SQLPOINTER db_alloc_buffer(SQLUINTEGER buffSize)
{
    SQLPOINTER Ptr = malloc(buffSize);
    if (Ptr == NULL) return NULL;
    memset(Ptr, ' ', buffSize); 
    return Ptr;
}
Emil Laine
  • 41,598
  • 9
  • 101
  • 157