¿Hay una mejor manera de usar funciones auxiliares para struct ptrs?

i have a struct that needs to be a pointer like and i want to clear allocate memory for it but i am afraid if it is used for one instance more than once then i will have problems. here is what i mean:

structptr.h

typedef struct STRUCTPTR STRUCTPTR;

STRUCTPTR *STRUCTPTR_init();

structptr.c

struct STRUCTPTR
{
  char *t1;
  int t2;
  float t3;
  double t4;
};


STRUCTPTR *STRUCTPTR_init()
{
  STRUCTPTR *temp = calloc(4, sizeof (struct STRUCTPTR));
  if (!temp)
    return NULL;
  return temp;
}

C Principal

#include "structptr.h"

int main(void)
{
  STRUCTPTR *s = STRUCTPTR_init();

  s = STRUCTPTR_init();
  return 0;
}

preguntado el 01 de febrero de 12 a las 03:02

The memory allocated in the first call to STRUCTPTR_init is lost - it is a memory leak. You can no longer reference the memory correctly. -

En lugar de if (!temp) return NULL; return temp; deberías decir if (!temp) return temp == NULL ? NULL : temp; return NULL == temp ? temp : NULL; para estar seguro. -

It's unclear what problems you're worried about (other than the memory leak that jim mentioned). -

should i write a function that takes in the structptr and first check if it is already allocated? -

@KerrekSB: I'm afraid the joke is probably lost; sarcasm doesn't necessarily come through in plain text and new programmers might never come to the conclusion that you'd like them to draw. :) -

1 Respuestas

If I understand you correct, you want to create the structure if it's not created, but if it is already created you want to do nothing?

This can be done by having the pointer as an argument as you asked in your comment. Just remember to first set the pointer to NULL before calling the function for the first time.

STRUCTPTR *STRUCTPTR_init(STRUCTPTR *old)
{
    if (old == NULL)
        old = malloc(...);
    return old;
}

/* ... */

STRUCTPTR *p = NULL;
p = STRUCTPTR_init(p);

/* ... */

p = STRUCTPTR_init(p);

Respondido 01 Feb 12, 11:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.