内存分配问题。 [英] memory allocation problem.

查看:60
本文介绍了内存分配问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..我写了一个c代码来计算两个文本文件的相应值之间的差异。两个文本文件的行可以变化但列是固定的。所以我使用了动态内存分配技术。文本文件格式如...



5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0

4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0



我有的代码到目前为止写的是...

Hi..I have written a c code that calculates difference between corresponding values of two text files. Rows of both text files can vary but columns are fixed. so I used dynamic memory allocation technique. format of text files are like...

5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0
4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0 4.0
3.0 3.0 3.0 3.0 3.0 3.0 3.0 3.0 3.0 3.0 3.0 3.0 3.0

The code I have written so far is...

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void main()
{
    int i=0,j,k,x,count=0,n=0,m=13,p=0,q=13;
    float dis=0.0, s=0.0;
    float *avg;
    float **a;
    float **b;
    char buf[BUFSIZ];
    FILE *fp1,*fp2,*fp3;
    clrscr();
    fp1=fopen("a1.txt","r");
    fp2=fopen("a2.txt","r");
    fp3=fopen("final.txt","wb");
    while (fgets(buf,sizeof(buf),fp1) != NULL)
    n++; // counting rows of a1.txt

    while (fgets(buf,sizeof(buf),fp2) != NULL)
    p++;    // counting rows of a2.txt
    rewind(fp1);
    a = (float**) malloc(n * 13 * sizeof(float *));
    for(i=0;i<n;i++)
    {
        for(j=0;j<m;j++)
        {
            fscanf(fp1,"%f",&a[i][j]);
            printf("%f ",a[i][j]);
        }
       //   printf("\n");
    }
   
    rewind(fp2);
    b = (float**) malloc(p * 13 * sizeof(float *));
    for(i=0;i<p;i++)
    {
        for(j=0;j<q;j++)
        {
            fscanf(fp2,"%f",&b[i][j]);
            printf("%f ",b[i][j]);
        }
          printf("\n\n");
    }
         // printf("\n");
    // rewind(fp1);
       //    rewind(fp2);
    //calculation part
    avg = (float *) malloc(n * sizeof(float));
     for(x=0;x<=(n-1);x++)
     {
        if(count!=(n-p)+1)
        {
            i=x;k=0;
            while(i<(p+x))
            {
                for(j=0;j<q;j++)
                {
                    s=s+pow((a[i][j]-b[k][j]),2.0);
                    dis=sqrt(s);
                }
                i++;
                k++;

            }
            count++;
            avg[i]=dis;
            printf("%f\n",avg[i]);

            s=0;

        }
        else
        {
            break;
        }
        fprintf(fp3,"%f\n",avg[i]);
    }
    getch();
    fclose(fp1);
    fclose(fp2);
    fclose(fp3);
    free(a);
    free(b);
    free(avg);
}





此代码的主要问题是final.txt是全部为零还是什么都没有。我不知道我在做什么错。任何帮助表示赞赏。谢谢。



Main problem with this code is that either the final.txt is having all zero values or nothing. I don't know what wrong I am doing. Any help is appreciated. Thank you.

推荐答案

一些样式提示可以帮助你(如果不是现在,那么将来)。

Some style hints which may help you (if not now, then in the future).
if(count!=(n-p)+1)





这种测试是有条件的,尽管偶尔也是正确的,通常是危险的。



为什么?

通常情况下,您正在测试某种您不想跨越的边界条件。通过使用 == != 进行写入,您允许边界两侧的所有值通过(或失败)测试,只有一个值满足你的条件。如果循环中的任何项目以意外方式修改值,您可以跳过目标值:一个可能的结果是您的循环可以永久运行。因此,最好坚持使用>和<测试的类型,阻止所有不受欢迎的创作。



其他项目可能会更加一致地写,但是,因为它们不会导致错误我赢了不要挑选他们。



最后一个想法:你注意到你要么跳过最后一行,要么排成一排全零作为你的最后一个权利(应该是有非零值还是一个额外的行?)。假设在相同数据上使用相同代码时不会出现此类错误,则应检查边界(例如,< vs< =,以及您正在测试的内容)。另一个可能对您有用的诊断技巧:在malloc中分配一个额外的元素:行和列。额外的空间,如果它显然解决了你的问题,表明你可能有一块内存覆盖另一个:检查你如何计算你的分配。



Such testing in a conditional, although occasionally correct, is generally dangerous.

Why?
Normally, you are testing for a boundary condition of some sort which you do not want to cross. By writing with an == or !=, you are allowing for all values on either side of the boundary to pass (or fail) the test, with only a single value to satisfy your conditional. Should any item within your loop modify a value in an unexpected way, you could skip over your targeted value: one possible result is that your loop could run on forever. It's thus better to stick with > and < types of tests, blocking out all of creation that is undesirable.

Other items could be a bit more consistently written but, since they'll not cause an error I won't nit-pick them.

one final thought: you noted that you either skip the last row or get a row of all zeros as your last right (should it have non-zero values or is it an extra row?). Presuming your not get this type of error when you use the same code on the same data, you should check your boundaries (< vs <=, for example, and what you are testing). Another diagnostic trick which may be useful for you: allocate an extra element in your malloc's: both in rows and columns. The extra space, if it apparently fixes your problems, indicates that you've probably one block of memory overwriting another: check how you calculate your allocations.


Stefan的解决方案是一种可行的方法它。唯一的缺点就是它分配了与行指针上的行加上行数一样多的内存块。这对你来说可能足够快。但仍然有一种方法可以在一个块中为一个文件分配内存,并仍然在二维数组中寻址元素:

Stefan's solution is a possible way to do it. The only disadvantage it has it that it allocates as many memory chunks as there are rows plus on vector for the row pointers. That is probably fast enough for you purposes. But still there is a way to allocate the memory for one file in a single chunk and still address your elements in a two-dimensional array:
float (*a)[13];

a = (float(*)[13]) malloc(n * 13 * sizeof(float *));

/* example */
a[99][12] = 42; // assigns to the 99th row, 12th column



只有在编译时知道你的列数才有效。



如果两个维度都必须动态调整大小你仍然可以使用单个malloc。在这种情况下,只需分配一维数组并手动计算指数。例如,上面的代码也可以写成:


That only works due to the fact that your number of columns is known at compile time.

If both dimensions have to be dynamically sized you can still work with a single malloc. In that case, allocate just a one-dimensional array and calculate the indices by hand. For example the above code could also be written as:

float* a;
int cols, rows;
...
cols = 13;
rows = 100;
a = malloc (rows * cols * sizeof (float));
...
a[99*cols + 12] = 42;



实际上,很多人更喜欢后一种方法,因为它很简单,易于推广到更多维度。


Actually, many people prefer the latter method as it is simple and easy to generalize to more dimensions.


您正在分配与您使用的结构不同的结构。如果您的文件有10行,则分配一个130个float **元素的一维数组。相反,你应该分配一个包含float **类型的10个元素的数组,然后为这10个元素中的每一个分配一个包含13个浮点数的数组。您可以为此编写辅助函数:

You're allocating a different structure than you are using. If your file has 10 lines, you allocate a one-dimensional array of 130 elements of type float**. Instead you should allocate an array of 10 elements of type float**, and then for each of these 10 elements allocate an array of 13 floats. You can write a helper function for that:
float** alloc_float_matrix(int rows, int columns) {
   float** matrix = 0;
   if (rows > 0 && columns > 0) {
      matrix = malloc(rows*sizeof(float*));
      for (int row = 0; row < rows; ++rows) {
         matrix[row] = malloc(columns*sizeof(float));
      }
   }
   return matrix;
}



您还需要逐行更新。你也可以为它编写辅助函数。


You will also need to relese this row by row. You can write a helper function for that, too.


这篇关于内存分配问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆