你好我正在使用c并且我在ubuntu中通过gcc编译它但是我的内存分配有一个奇怪的错误我的代码:
int INIT_NETWORK(int * layer_number,int layer_size){
int i,j,k;
//check if the data from user is valid
if(layer_size<=0)
return -1;
for(i=0;i<layer_size;i++)
if(layer_number[i]<=0)
return -1;
layers_count=layer_size;
// allocate the layers structures
layer=(struct layers*) malloc(layer_size* sizeof(struct layers));
if(layer==NULL)
return -1;
//allocate the neurals for the layers
for(i=0;i<layer_size;i++)
{
layer[i].size=layer_number[i];
layer[i].neural=(struct neurals *) malloc(sizeof(struct neurals)*layer_number[i]);
if(layer[i].neural==NULL)
return -1;
if(i==layer_size-1)
break;
layer[i].weight=(struct matrix **) malloc(layer_number[i]*sizeof(struct matrix *));//allocate weight raw
if(layer[i].weight==NULL)
return -1;
for(j=0;j<layer_number[i];j++)
{
layer[i].weight[j]=(struct matrix *) malloc(layer_number[i+1]*sizeof(struct matrix));//allocate weight column
if(layer[i].weight[j]==NULL)
return -1;
for(k=0;k<layer_number[i+1];k++)//give the weights and the bais random values.
{
layer[i].weight[j][k].weightV=(double) 3/(rand()%20+1)-1.5;
}
}
layer[i].neural[j].bais=3/(rand()%20+1) -1.5;
}
for(j=0;j<layer_number[i];j++)
layer[i].neural[j].bais=3/(rand()%20+1)-1.5;
output_val=(double *)malloc(sizeof(double)*layer[i].size);
if(output_val==NULL)
return -1;
layer[i].weight=NULL;//the output layer doesn't have weights.
//we have a bug here by the pointer.
for(k=0;k<layers_count;k++){
printf("on layer:%d\n",k);
for(j=0;j<layer[k].size;j++)
{
for(i=0;i<layer[k+1].size;i++)
printf("%lf\t",layer[1].weight[j][i].weightV);
printf("|\n");
}
}
return 0;
}
以及我使用它的结构和数据:
//define the neurals structure
struct neurals{
double x;//the input
double a;//the output
double bais;
};
//define struct for both weight and deltaW
struct matrix{
double weightV;
double deltaW;
};
//define the layers structure
struct layers{
struct neurals * neural;//pointer to array of neural for a single layer
uint16 size;
struct matrix ** weight;//the weight's matrix for this layer and the next one
};
struct layers * layer=0;
uint16 layers_count;
double * output_val=0;
问题出在输出中: 在图层上:0 -0.750000 -1.071429 -1.333333 -1.312500 | 分段错误(核心转储)
但奇怪的是,当我尝试可以将值分配给我可以的数据,我可以直接打印它。但当我退出循环并尝试打印它或当我尝试将我的数据发送到另一个功能时,我可以计算我的第一个原始。
我尝试打印我分配的地址和结果:
on layer:0
0x559bc6b43350 |
0xbff8000000000000 |
0x559bc6b433f0 |
on layer:1
0xbff8000000000000 |
0x559bc6b43540 |
0x559bc6b435a0 |
0x559bc6b43600 |
on layer:2
0x559bc6b43710 |
0xbff8000000000000 |
0x559bc6b43790 |
0x559bc6b437d0 |
0x559bc6b43810 |
on layer:3
0x559bc6b438c0 |
0x3ff8000000000000 |
0x559bc6b43900 |
为什么他们中的一些人有相同的地址?