LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C advice requested (https://www.linuxquestions.org/questions/programming-9/c-advice-requested-570411/)

freeindy 07-18-2007 10:21 AM

C advice requested
 
Hi,

I have a simple question, hopefully with a simple answer.

I have a structure:
Code:

struct INFO
{
  int ID;
  struct INFO* pNext;
}

And, I would like to have a function in this manner:

Code:

bool updateInfo(struct INFO* pInfo)
{
 //UPDATE...
}

The question is, should the caller be recommended for allocating the memory OR should the memory be allocated within updateInfo() and all the info should be copied?

Any help is appreciated.

Indy

theNbomr 07-18-2007 11:18 AM

Use the greatest possible flexibility:
In updateInfo(), if the pointer is non-null, assume it has been allocated, else allocate storage from malloc()/calloc(). Wherever the storage is allocated, assign NULL to the pNext member.
--- rod.

paulsm4 07-18-2007 03:45 PM

Uh, no.

The way you have it designed, the caller *must* allocate the space; the callee *cannot* allocate it:
Code:


bool updateInfo(struct INFO* pInfo)
{
 //UPDATE...
}

...

void someOtherProc ()
{
  struct INFO *p = (struct INFO *)malloc (sizeof (struct INFO));
  if (p != NULL)
    updateInfo (p);
    ...

Suppose you did the "malloc()" inside updateInfo()? How is the caller going to get the new pointer, the one returned by "malloc()"? Certainly not through the "pInfo" parameter. You can change the *local* value of "pInfo" in "updateInfo()" ... but you cannot return the new value back to the caller.

Two alternatives might be:
a) make pInfo a pointer to a pointer ("struct INFO **ppInfo")
... or ...
b) make "udpateInfo()" return the pointer (instead of a "bool").

If your function simply "updates existing data", then like your original design better. Just allocate the struct before you call "updateInfo()", and Life is Good.

Otherwise, if your function is actually "add new member to list", then I'd allocate inside the function ... and pass a pointer to a pointer. Here's an example:

http://vergil.chemistry.gatech.edu/r...ial/lists.html


IMHO .. PSM

exvor 07-18-2007 05:06 PM

From what I can tell he is just updating the info in an existing list element in that case you could just modify the info directly. But then you ask about allocating memory and that is confusing as you wouldn't need to.

freeindy 07-19-2007 05:19 AM

Thanks lads,

actually, paulsm4, i am allocating a new structure inside the updateInfo. So basically, I'm adding a structure inside a structure like:

Code:

struct DATA
{
  ...
  struct INFO* info;
  ...
  struct DATA* next;
  struct DATA* prev;
}

So exvor, thanks. It makes sense. I wanted to be sure. The caller should allocate.

Indy


All times are GMT -5. The time now is 05:12 PM.