Reputation:
Take a look at this example function:
RuntimeConfiguration* conf_rt_conf() {
RuntimeConfiguration *conf;
conf = new RuntimeConfiguration();
conf->arch_path="./archive";
conf->err_log="./err_log";
conf->fail_log="./fail_log";
conf->msg_log="./msg_log";
conf->save="html, htm, php";
conf->ignore="jpg, gif";
conf->cookies="";
return conf;
}
Everything here works fine, but when I run something like this:
DatabaseInput** conf_db_input() {
DatabaseInput **db_input;
db_input=(DatabaseInput **)malloc(NUMB_SITES*sizeof(DatabaseInput *));
for (int i=0;i<NUMB_SITES;i++) db_input[0]= new DatabaseInput();
db_input[0]->full_name="ABCNews";
db_input[0]->alias="abcn";
db_input[0]->prefix="/eng";
db_input[1]->full_name="Rzeczpospolita";
db_input[1]->alias="rp";
db_input[1]->prefix="/pol";
return db_input;
}
I get segmentation fault on first assignment. It probably has something to do with the fixed memory block allocated for this struct. How do I get it to work properly?
Upvotes: 1
Views: 1739
Reputation:
db_input[0]= new DatabaseInput();
It actually had the i instead of 0, I just tried several things out, and missed that zero there when copying source code, so that's not the answer.
===EDIT===
db_input = new DatabaseInput*[NUMB_SITES];
That worked, thanks Gaston :)
Upvotes: 0
Reputation: 1848
Maybe this:
DatabaseInput *db_input[];
db_input = new DatabaseInput*[NUMB_SITES]; // Creates an array of pointers
for (int i=0; i<NUMB_SITES; i++) db_input[i]= new DatabaseInput();
could work? (I didn't test it)
Note, to free the memory used, you should do something like:
for (int i=0; i<NUMB_SITES; i++) delete db_input[i];
delete[] db_input;
Upvotes: 1
Reputation: 80770
We can't determine the error without more details. But a few remarks:
Upvotes: 0
Reputation: 1842
At first look
db_input[0]= new DatabaseInput();
I think it should be
db_input[i]= new DatabaseInput();
It is also recommended to check the result of the malloc operation
Upvotes: 2
Reputation:
Your code prompts several questions:
Upvotes: 3
Reputation: 882776
I'd change
for (int i=0;i<NUMB_SITES;i++) db_input[0]= new DatabaseInput();
to this for a start:
for (int i=0;i<NUMB_SITES;i++) db_input[i]= new DatabaseInput();
Upvotes: 6
Reputation: 400159
First ... Did you never hear about (default) constructors? This reads like C code using "new", which is always a bit scary.
Second, all your newly allocated structures are stored at db_input[0]
, which seems wrong.
Upvotes: 2