omer
omer

Reputation: 1440

Which convention is better in C programming?

My question refers to the topic of C pointers. Imagine the following scenario: I have a struct variable named "stc" defined like this:

struct stc {
       int data;
       char ch;
}

declared in the beginning of the Main() function in my program. I would like to set the values the fields in the struct (i.e. data) using a function.

Now my question is which of the following convention is better and why?

Convention 1: Write a function the return a pointer of type stc:

struct stc *func(int d, char c)
{
    stc *tmp = malloc(sizeof(stc))
    tmp -> data = d;
    tmp -> ch = c;

    return tmp;
}

and later on free the allocated memory when the structure is no longer needed.

Convention 2: Write a function that receives a pointer to the struct and send it the address of stc

void func(stc *stcP, int d, char c)
{
     stcP -> data = d;
     stcP -> ch = c;
}

Thanks a lot!

Upvotes: 4

Views: 191

Answers (3)

sr01853
sr01853

Reputation: 6121

The first type is more prone to memory leaks. It is a better practise to free the memory from where it was malloc'ed. The second approach looks neat and void func(stc *stcP, int d, char c) does the intended task of initializing the structure.

Upvotes: 2

Jens Gustedt
Jens Gustedt

Reputation: 78903

I'd have both, or variants of it:

typedef struct stc stc;


#define STC_INITIALIZER(D, C) { .data = d, .ch = c, }

stc* stc_init(stc *stcP, int d, char c) {
  if (stcP) {
     *stcP = (stc)STC_INITIALIZER(d, c);  // Initialize with a compound literal
  }
  return stcP;
}

stc* stc_allocate(int d, char c) {
  return stc_init(malloc(sizeof(stc)), d, c);
}

So this has the advantage that you may use the same init function for malloced objets as for other variables.

Also note that you had an error in your code, in C you can't use stc without struct unless you typedef it beforehand.

Upvotes: 4

Yu Hao
Yu Hao

Reputation: 122373

The first usage could cause memory leak without care.

The second usage is better, but you use the arrow operator incorrectly, it should be:

void func(stc *stcP, int d, char c)
{
    stcP -> data = d;
    stcP -> ch = c;
}

Upvotes: 5

Related Questions