The problem is that malloc
may return NULL
when it fails. In this case, writing to a->inputs
in the following line would be dereferencing the NULL
pointer, which is Undefined Behavior, and should be avoided. It's admittedly unlikely that malloc
will fail, but since you like to write safe code, you should be testing the return value of malloc
:
A* a = (A*)malloc(sizeof(A));
if (a != NULL){
a->inputs = inputs;
} else {
/* Handle error */
}
Since you're writing C++ coming from a C background, you should be aware that the code you're writing is essentially still C, and is very different from modern C++, in which we do lots of things very differently. In C++, there are lots of very helpful tools and idioms we like to use.
I'm assuming that inputs
is a list of numbers. In C++, I would rewrite your code as follows:
// no typedef
struct A {
vector<double> inputs;
};
// no createA
// Example usage:
int main(){
A a;
// no manual memory management!!!
// no pointers!
// how many inputs?
cout << "There are " << a.inputs.size() << " inputs\n";
// add two inputs
a.inputs.push_back(3.83);
a.inputs.push_back(1.01);
// print everything
for (const auto& input : a.inputs){
cout << input << " ";
}
return 0;
}
This how we usually do things in C++ nowadays. There's lots of things going on under the hood, but the overall experience is very safe and friendly once you know what you're doing. If you're interested, I would suggest that you take your pick from this list of good C++ books and read carefully. Otherwise, it might be simplest to stick to C, if that's what you're comfortable with.