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?
First of all, you should properly format the code in your question.
You need to dynamically allocate this object:
SomeType *a = malloc(sizeof(*a));
and
return a;