Malloc调用分配已在使用中的地址。

huangapple go评论77阅读模式
英文:

Malloc calls allocate addresses already in use

问题

简介

我遇到了一个奇怪的问题,我正在编写以下代码,它要求用户输入一个矩阵,程序会要求输入大小,然后输入矩阵的元素。

随后,我再次遍历矩阵以计算每行的最大最小数字,以及主对角线上元素的总和。

我正在编写这个程序,以便稍后将其翻译成汇编语言,这就是为什么我在矩阵中使用指针,以使程序尽可能接近汇编代码的原因。

#include <stdlib.h>
#include <stdio.h>;

int main(){

    int rows, cols;
    int *matrix;
    int *max, *min, diag, num;

    // 输入矩阵
    printf("行数: ");
    scanf("%d", &rows);
    printf("列数: ");
    scanf("%d", &cols);

    // 分配矩阵
    matrix = malloc(rows*cols);
    max = malloc(rows);
    min = malloc(rows);

    // 填充矩阵
    for (int i=0; i<rows; i++)
        for (int j=0; j<cols; j++){
            printf("[%d, %d] = ", i, j);
            scanf("%d", matrix+(i*cols)+j);  // 存储在偏移位置
        }

    diag = 0;
    for (int i=0; i<rows; i++){
        max[i] = matrix[i*cols];  // 假设第一个是最大值
        min[i] = matrix[i*cols];  // 假设第一个是最小值
        for (int j=0; j<cols; j++){
            num = *(matrix+(i*cols)+j);  // 临时存储矩阵中的数字以便快速访问
            if (i == j) diag += num;  // 如果在主对角线上,将其添加到对角线总和
            if (num > max[i]) max[i] = num;
            else if (num < min[i]) min[i] = num;
        }
    }

    printf("\n[2,2] 处的值为 %d\n\n", matrix[8]);

    for (int i=0; i<rows; i++){    
        for (int j=0; j<cols; j++){
            printf("%d ", *(matrix+(i*cols)+j));
        }
        printf("| 最大值=%d, 最小值=%d", max[i], min[i]);
        printf("\n");
    }

    printf("\n对角线总和 = %d");

    return 0;
}

使用3x3输入的屏幕截图
Malloc调用分配已在使用中的地址。

使用4x4输入的屏幕截图
Malloc调用分配已在使用中的地址。

问题

当我输入一个3x3矩阵的元素,其中矩阵的值从1到9,最后一个元素出现错误,显示值3而不是9

我尝试了其他输入,似乎问题是复制第一行、第三列的值。

这让我很困扰,因为当我使用调试器运行时,程序的运行是符合预期的。

解决方案

如果我将矩阵定义为数组(int matrix[i][j])或maxmin数组,问题就会解决,但这不是我想要的解决方案。

如果我分配矩阵时留出一些额外的空间,问题也会消失。再次强调,这不是一个理想的解决方案。

假设

我认为,除了我弄错了一些东西之外,第二次调用mallocmax = malloc(rows))正在分配数组,覆盖了上一行代码中分配矩阵的malloc调用。

注意

感谢大家的帮助,请联系我获取有关此问题的额外信息。

英文:

Introdution

I've ran into a weird issue, I was writting the following code that requestes the user a matrix, the program asks for the size, then the elements in the matrix.

Later, I itrerate the matrix again to calculate the max and min number in each row and also the sum of the elements in the main diagonal.

> I'm writting this program to translate later to assembly that is why I am using pointers for my matrix, to keep the program as closest as it will be in assembly

#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;


int main(){

    int rows, cols;
    int *matrix;
    int *max, *min, diag, num;

    // Input matrix
    printf(&quot;Rows number: &quot;);
    scanf(&quot;%d&quot;, &amp;rows);
    printf(&quot;Cols number: &quot;);
    scanf(&quot;%d&quot;, &amp;cols);

    // Alloc matrix
    matrix = malloc(rows*cols);  
    max = malloc(rows);  
    min = malloc(rows);  

    // Fill matrix
    for (int i=0; i&lt;rows; i++)
        for (int j=0; j&lt;cols; j++){
            printf(&quot;[%d, %d] = &quot;, i, j);
            scanf(&quot;%d&quot;, matrix+(i*cols)+j);  // Store at offset
        }

    diag = 0;
    for (int i=0; i&lt;rows; i++){
        max[i] = matrix[i*cols];  // Assume 1st is max
        min[i] = matrix[i*cols];  // Assume 1st is min
        for (int j=0; j&lt;cols; j++){
            num = *(matrix+(i*cols)+j);  // Store num of the matrix temporaly for fast access
            if (i == j) diag += num;  // If in main diagonal, add to diag sum
            if (num &gt; max[i]) max[i] = num;
            else if (num &lt; min[i]) min[i] = num;
        }
    }

    printf(&quot;\nDEBUG for [2,2] value %d\n\n&quot;, matrix[8]);

    for (int i=0; i&lt;rows; i++){    
        for (int j=0; j&lt;cols; j++){
            printf(&quot;%d &quot;, *(matrix+(i*cols)+j));
        }
        printf(&quot;| max=%d, min=%d&quot;, max[i], min[i]);
        printf(&quot;\n&quot;);
    }

    printf(&quot;\nDiagonal sum = %d&quot;, diag);


    return 0;
}

Screenshoot with 3x3 input
Malloc调用分配已在使用中的地址。

Screenshoot with 4x4 input
Malloc调用分配已在使用中的地址。

Issue

When I type the elements for a 3x3 matrix with the elements from 1 to 9 as the matrix values, the last element bugs and shows the value 3 instead of 9.

I've tried with other inputs and the bug seems to be copying the value from the 1st row, 3rd col.

This drives me crazy because when I run it with the debugger, the program works as expected.

Workaround solutions

The probles solves if I define the matrix as an array (int matrix[i][j]) or the max and min arrays, but that is not the solution I want.

Also if I allocate the matrix with some extra space, the problem is gone. Again, an unwanted solution.

Hypothesis

I think that, apart from me messing something up, the second call to malloc (max = malloc(rows)) is allocating the array overwritting the previous malloc call, the one that allocated the matrix in the previous line.

Note

Thank everyone for helping, contact me for extra information about the issue

答案1

得分: 2

The workarounds are on the right track in terms of understanding the underlying issue, it's about space. You need to malloc enough bytes to store the ints.

How many bytes? If a single int occupied one byte of memory then the answer would be rows * cols (which is where you are now). But that's not the case, an int actually occupies either two bytes or four bytes (usually four, but it depends on the compiler). Use sizeof to determine the size of an int and factor this into the calculation.

Thus:

    matrix = malloc(sizeof(int) * rows * cols);  
    max = malloc(sizeof(int) * rows);  
    min = malloc(sizeof(int) * rows);
英文:

The workarounds are on the right track in terms of understanding the underlying issue, it's about space. You need to malloc enough bytes to store the ints.

How many bytes? If a single int occupied one byte of memory then the answer would be rows * cols (which is where you are now). But that's not the case, an int actually occupies either two bytes or four bytes (usually four, but it depends on the compiler). Use sizeof to determine the size of an int and factor this into the calculation.

Thus:

    matrix = malloc(sizeof(int) * rows * cols);  
    max = malloc(sizeof(int) * rows);  
    min = malloc(sizeof(int) * rows);

huangapple
  • 本文由 发表于 2023年4月1日 00:57:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定