Search code examples
cstructmallocfree

automatic allocation in c


1  #define SOME_OPERATION(a,b) a+b
2
3  typedef struct {
4   char* name;
5   int nameLen;
6   int val;
7  } SomeType;
8
9  SomeType* f(int x, int y, int z, char* name)
10 {
11  SomeType a;
12
13  assert(name != NULL);
14  a.name = malloc(strlen(name) + 1);
15  strcpy(a.name, name);
16  assert( (a.nameLen = strlen(name)) > 0 );
17
18  a.val = SOME_OPERATION(x,y) * z;
19  if (a.val < 0) {
20  return NULL;
21 }
22
23 return &a;
24 }

This code compiles successfully, but contains a number of significant errors. For example in line 14, there it doesn't check if malloc returns NULL. My question is, if this fixed code works for this specific issue:

if(!a.name)
{
  //or should be in addition free(a)
  return NULL;
}

When I write SomeType a, Does it mean that a new pointer to SomeType was allocated?


Solution

  • First of all, you should properly format the code in your question.

    1. You return a reference to the automatic variable. This variable does not exist after the function return. It is undefined behaviour.

    You need to dynamically allocate this object:

    SomeType *a = malloc(sizeof(*a));
    

    and

    return a;