如果我不释放动态分配的内存,我的程序可以工作,但是当我试图释放它时,它崩溃了。我在dev - c++上运行我的代码,错误信息没有帮助:一个问题使程序停止工作。问题在代码的末尾。如果我去掉释放部分,程序就能正常运行。下面是一个示例输入:
5
2.3
1.4 8.2
3.1 2.0 7.7
5.3 6.1 4.4 1.2
5.5 6.1 3.0 2.3 4.9
代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(void) {
int ordem;
scanf("%d", &ordem);
double **vetor; //apontador para apontador (jagged array)
double soma = 0;
int elementos;
elementos = (ordem*ordem + ordem) / 2;
vetor = malloc(ordem * sizeof(double*)); //o primeiro endereço do vetor é seu local de memória, que define quantos pointers ele terá (ordem)
int n, m;
for (n = 0; n < ordem; n++) {
*(vetor + n) = malloc(n * sizeof(double));
}
for (n = 0; n < ordem; n++) {
for (m = 0; m <= n; m++) {
scanf("%lf", *(vetor + n) + m);
soma = soma + *(*(vetor + n) + m);
}
}
double media = soma / (double) elementos;
double aux = 0;
for (n = 0; n < ordem; n++) {
for (m = 0; m <= n; m++) {
aux = aux + pow((media - vetor[n][m]), 2);
}
}
double desvio = sqrt(aux / ((double)elementos));
for (n = 0; n < ordem; n++) {
for (m = 0; m <= n; m++) {
printf("%.12lf ", (vetor[n][m] - media) / desvio);
}
printf("n");
}
printf("n%.12lf %.12lf n", media, desvio);
for (n = 0; n < ordem; n++) {
free(*(vetor + n));
}
free(vetor);
return 0;
}
差不多就是这样了。我不知道该怎么解决。我不认为dealloc有同样的效果。我更喜欢免费。我发现了新的信息:对于样本输入,我可以释放((向量+ 0)),((向量+ 1))和(*(向量+ 2)),但不能释放3和4。这就意味着向量在这两个地方出了问题
修改如下:
for (n = 0; n < ordem; n++) {
*(vetor + n) = malloc(n * sizeof(double));
}
:
for (n = 0; n < ordem; n++) {
*(vetor + n) = malloc((n + 1) * sizeof(double));
}
原因是n
在第一次迭代中为ZERO,因此您请求malloc()
为您分配零字节。
BTW,这是我通常用来避免犯这种错误的方法:2d-dynamic-array-c.
输出:C02QT2UBFVH6-lm:~ gsamaras$ gcc -Wall main.c
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
5
2.3
1.4 8.2
3.1 2.0 7.7
5.3 6.1 4.4 1.2
5.5 6.1 3.0 2.3 4.9
-0.892202112506
-1.307537578672 1.830552610141
-0.523015031469 -1.030647267895 1.599810684493
0.492249441383 0.861436522419 0.076913975216 -1.399834348932
0.584546211642 0.861436522419 -0.569163416599 -0.892202112506 0.307655900864
4.233333333333 2.166923061753
C02QT2UBFVH6-lm:~ gsamaras$
您已经收到了您的答案,但是还有其他几个领域,您确实需要验证您的输入和分配,如果您要有任何信心,您的代码正在使用实际值,而不是写入到您的硬件内存的未知部分。总是总是验证用户输入和内存分配。只需要几行额外的代码就可以了,例如:
int ordem;
if (scanf ("%d", &ordem) != 1) {
fprintf (stderr, "error: invalid input (ordem)n");
return 1;
}
double **vetor,
soma = 0;
int elementos, n, m;
elementos = (ordem * ordem + ordem) / 2;
if (!(vetor = malloc (ordem * sizeof *vetor))) {
fprintf (stderr, "error: virtual memory exhausted.n");
return 1;
}
for (n = 0; n < ordem; n++)
if (!(*(vetor + n) = malloc ((n + 1) * sizeof **vetor))) {
fprintf (stderr, "error: virtual memory exhausted.n");
return 1;
}
for (n = 0; n < ordem; n++) {
for (m = 0; m <= n; m++) {
if (scanf ("%lf", *(vetor + n) + m) != 1) {
fprintf (stderr, "error: invalid input (vetor + %d)n", n);
return 1;
}
soma = soma + *(*(vetor + n) + m);
}
}