简体   繁体   English

尽管使用 calloc(),为什么我得到垃圾值?

[英]Why am I getting junk values despite using calloc()?

I would like to know why the first two elements are always non-zero.我想知道为什么前两个元素总是非零。 I don't know how more I can describe the question, but this is not allowing me to post the question, so I'm writing this.我不知道我还能如何描述这个问题,但这不允许我发布这个问题,所以我正在写这个。 Not sure if this will work.不确定这是否可行。

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

#define SIZE 3

void printMatrix(int **m)
{
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++)
            printf("%d ", m[i][j]);
        printf("\n");
    }
}

int main(int argc, char const *argv[])
{
    int **matrix;

    matrix = (int **) calloc(sizeof(int), SIZE);

    for (int i = 0; i < SIZE; ++i)
        matrix[i] = (int *) calloc(sizeof(int), SIZE);

    printf("%s\n", "Matrix initialized.");

    printMatrix(matrix);

    return 0;
}

Output: Output:

Matrix initialized.
1371548192 32653 0 
0 0 0 
0 0 0

You're not allocating enough memory:您没有分配足够的 memory:

matrix = (int **) calloc(sizeof(int), SIZE);

Here you're attempting to create an array of 3 int * , but you're only allocating space for 3 int .在这里,您尝试创建一个 3 int *数组,但您只为 3 int分配空间。 If a pointer is larger than an int on your system, which it most likely is, you write past the end of the array when you create the arrays for each row.如果指针大于系统上的int (很可能是这样),则在为每一行创建 arrays 时写入数组的末尾。 Writing past the end of allocated memory invokes undefined behavior .写入分配的 memory 的末尾会调用未定义的行为

Since you're creating an array of int * , use that for the size of each element:由于您正在创建一个int *数组,因此将其用于每个元素的大小:

matrix = calloc(sizeof(int *), SIZE);

Also, don't cast the return value of malloc / realloc / calloc , as that can mask a bug if you forget to #include <stdlib.h>另外,不要malloc / realloc / calloc的返回值,因为如果你忘记#include <stdlib.h>会掩盖错误

The code uses calloc(sizeof(int), SIZE) , but the actual datatype in the structure is int * , leading to insufficient memory allocation on some systems (mine gives int size as 4 and int * size as 8).该代码使用calloc(sizeof(int), SIZE) ,但结构中的实际数据类型是int * ,导致在某些系统上 memory 分配不足(我的int size 为 4, int * size 为 8)。

Here's a rewrite suggestion (we'll swap size parameters in the calloc call per its header):这是一个重写建议(我们将在calloc调用中根据其标头交换大小参数):

int main(int argc, char const *argv[]) {
    int **matrix;

    if (!(matrix = calloc(SIZE, sizeof(*matrix)))) { 
        fprintf(stderr, "calloc failed");
        return 1;
    }

    for (int i = 0; i < SIZE; ++i) {
         if (!(matrix[i] = calloc(SIZE, sizeof(*(matrix[i]))))) {
            fprintf(stderr, "calloc failed");
            return 1;
        }
    }

    printf("%s\n", "Matrix initialized.");
    printMatrix(matrix);
    return 0;
}

Here, we use *matrix and *matrix[i] instead of hard coding the types int * and int respectively.在这里,我们使用*matrix*matrix[i]而不是分别对类型int *int进行硬编码 This can help us avoid bugs and hunting for locations to change code if we need to make type adjustments at some point.如果我们需要在某些时候进行类型调整,这可以帮助我们避免错误并寻找更改代码的位置。

We also check that calloc succeeds by testing that the pointer is non-NULL.我们还通过测试指针是否为非 NULL 来检查calloc是否成功。 Failing to do so can introduce difficult-to-find bugs due to undefined behavior.不这样做可能会由于未定义的行为而引入难以发现的错误。

Note Do I cast the result of malloc ?注意我是否投射malloc的结果? . .

Reference manual describes calloc as:参考手册将calloc描述为:

void* calloc (size_t num, size_t size);

So, calloc takes firstly num of elements and then size of a particular element因此, calloc首先num元素的数量,然后获取特定元素的size

Try:尝试:

matrix = (int **) calloc(SIZE, sizeof(int *));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我在此列表中得到垃圾值 - Why am I getting junk values in this list 当我连字符串时,为什么我会收到垃圾字符? - Why am I getting junk characters when I concat a string? 为什么我不能在我用 calloc 创建的分配内存中写入? - Why am I not able to write in the allocated memory that I created with calloc? 为什么我使用 calloc() function 为 5 个元素动态分配空间时却能给出 6 个元素? - Why am I able to give 6 elements when I am dynamically allocating space for only 5 elements using calloc() function? 为什么我得到垃圾值? - Why am I getting garbage values? 当我从 function 返回时尝试打印新数组时,我得到了垃圾 - I am getting junk when I try to print the new array when i return it from function 为什么我在输出后得到一些随机值? - Why am I getting some random values after the output? 编写程序以查看二进制数据。 我这样做正确还是获取垃圾数据? - Wrote a program to view binary data. Did I do this correctly or am I getting junk data? 将值写入数组时为什么会出现错误? - Why am I getting an error when writing values to an array? 如果我将 malloc 和 calloc 用于浮点变量并将其分配给 int 那么其余的 2 个字节会发生什么? - If I am using malloc and calloc for a float variable and assign it to int then what will happen to the rest of the 2 bytes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM