“违反写权限";在函数内部使用malloc()之后 [英] "Write Acces Violation" After Using malloc() Inside a Function

查看:54
本文介绍了“违反写权限";在函数内部使用malloc()之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2D矩阵的自定义结构.我在函数内部使用此结构来初始化2D矩阵,其中每个元素值都设置为0.我还有另一个函数可以将矩阵打印到终端(出于调试目的).

I have custom struct for 2D Matrices. I'm using this struct inside a function to initialize a 2D matrix where every element value is set to 0. I've also have another function to print a matrix to terminal (for debugging purposes).

当我在main.c 内部编写结构和函数时,它们就起作用了.问题是,当我将它们放在单独的文件中并从该文件中调用它们时,我收到运行时错误:抛出异常:写访问冲突.

When I write the struct and the functions inside the main.c, they work. The problem is when I put them in a separate file and call them from that file I get a runtime error: Exception thrown: write access violation.

在我的程序中,我有3个文件: main.c my_lib.h my_lib.c .该结构存储在 my_lib.h 内部,并且函数位于 my_lib.c 中.在 main.h

In my program I have 3 file: main.c, my_lib.h, my_lib.c. The struct is stored inside my_lib.hand the function is in my_lib.c. Inside main.h

我正在使用Windows 10&Visual Studio 2017 v15.9.10中进行编码

I'm using Windows 10 & coding in Visual Studio 2017 v15.9.10

程序会编译,但会给出运行时错误抛出异常:写访问冲突

The program compiles but gives a runtime error Exception thrown: write access violation

好吧,这似乎是我自己的错.

Well, it seems it was my own fault that this was happening.

实际上,我试图在我的工作计算机上运行此代码.我已经将原始代码写在我的个人计算机上,其中分别是 main.c my_lib.h & my_lib.c 版本正在运行.然后,我复制了正在使用的文件夹,并尝试继续在工作计算机上使用.我的两台计算机都在Windows 10操作系统上运行,并且都具有相同版本的VS 2017.

Actually, I was trying to run this code on my work computer. I've written the the original code on my personal computer where the main.c, my_lib.h & my_lib.c version was working. Then I copied the folder that I was working on and tried to continue on my work computer. Both my computer runs on Windows 10 OS and both have the same version of VS 2017.

在我的个人计算机上,解决方案资源管理器如下:

On my personal computer the solution explorer was like:

但是在我的工作计算机上,解决方案打开为:

But on my work computer, the solution opened as:

两台计算机上的所有内容(包括文件夹层次结构)都相同.看来,复制项目文件夹不是一个好主意.

Everything, including the folder hierarchy are same on both computers. It seems, copying a project folder is not a good idea.

当我在工作计算机上创建一个新的C项目并手动添加 my_lib.c my_lib.h 时,一切正常.

When I, created a new C project on my work computer and added the my_lib.cand my_lib.h manually, everything worked.

但是我仍然很好奇为什么会出现Exception错误...并且如何在不使用VS创建新项目的情况下解决复制问题呢?

But I'm still curious why I was getting an Exception error... And how can I correct this problem of copying without creating a new project in VS?

main.c

#include <stdio.h>

typedef struct Matrix {
    int rows; // number of rows
    int cols; // number of columns
    double** data; // a pointer to an array of n_rows pointers to rows
}Matrix;

Matrix* make_matrix(int n_rows, int n_cols);
void print_matrix(Matrix* m);

int main() {

    Matrix* m1 = make_matrix(2, 5);

    print_matrix(m1);

    return 0;
}


// CREATE A MATRIX WITH N_ROWS AND N_COLUMNS AND INITIALIZE EACH VALUE AS 0
Matrix* make_matrix(int n_rows, int n_cols) {
    Matrix* matrix = malloc(sizeof(Matrix));
    matrix->rows = n_rows;
    matrix->cols = n_cols;
    double** data = malloc(sizeof(double*) * n_rows);
    for (int x = 0; x < n_rows; x++) {
        data[x] = calloc(n_cols, sizeof(double));
    }
    matrix->data = data;
    return matrix;
}

// PRINT GIVEN MATRIX TO COMMAND LINE
void print_matrix(Matrix* m) {
    for (int x = 0; x < m->rows; x++) {
        for (int y = 0; y < m->cols; y++) {
            printf("%f", m->data[x][y]);
            printf("|");
        }
        printf("\n");
    }
}

main.c&单独文件中的功能(引发异常)

main.c

#include "my_lib.h"
int main(){
        // Create a 2 by 5 matrix & then print it to terminal
        Matrix* m1 = make_matrix(2, 5);
        print_matrix(m1);
        return 0;
}

my_lib.h

#pragma once

// Our custom 2D matrix struct
typedef struct Matrix {
    int rows; // number of rows
    int cols; // number of columns
    double** data; // a pointer to an array of n_rows pointers to rows
}Matrix;

Matrix* make_matrix(int n_rows, int n_cols);
void print_matrix(Matrix* m);

my_lib.c

#include "my_lib.h"
#include <stdio.h>

// CREATE A MATRIX WITH N_ROWS AND N_COLUMNS AND INITIALIZE EACH VALUE AS 0
Matrix* make_matrix(int n_rows, int n_cols) {
    Matrix* matrix = malloc(sizeof(Matrix));
    matrix->rows = n_rows;
    matrix->cols = n_cols;
    double** data = malloc(sizeof(double*) * n_rows);
    for (int x = 0; x < n_rows; x++) {
        data[x] = calloc(n_cols, sizeof(double));
    }
    matrix->data = data;
    return matrix;
}

// PRINT GIVEN MATRIX TO COMMAND LINE
void print_matrix(Matrix* m) {
    for (int x = 0; x < m->rows; x++) {
        for (int y = 0; y < m->cols; y++) {
            printf("%f", m->data[x][y]);
            printf("|");
        }
        printf("\n");
    }
}

推荐答案

崩溃的原因与项目中只有一个或两个.c文件完全无关,但这是因为您忘记了包含 my_lib.c 中的< stdlib.h> .

The reason you get the crash is not related at all to the fact that you have one or two .c files in your project but it's because you forgot to include <stdlib.h> in my_lib.c.

这会触发以下警告:

my_lib.c(8):警告C4013:'malloc'未定义;假设外部返回int
my_lib.c(13):警告C4013:'calloc'未定义;假设extern返回int
my_lib.c(13):警告C4047:'=':'double *'在间接级别上与'int'不同
my_lib.c(8):警告C4047:正在初始化":矩阵*"不同来自'int'的间接访问级别
my_lib.c(11):警告C4047:'initializing':'double **'的间接级别与'int'

my_lib.c(8) : warning C4013: 'malloc' undefined; assuming extern returning int
my_lib.c(13): warning C4013: 'calloc' undefined; assuming extern returning int
my_lib.c(13): warning C4047: '=': 'double *' differs in levels of indirection from 'int'
my_lib.c(8): warning C4047: 'initializing': 'Matrix *' differs in levels of indirection from 'int'
my_lib.c(11): warning C4047: 'initializing': 'double **' differs in levels of indirection from 'int'

您可以在32位版本上使用它,因为 int 的大小与指针的大小相同.

You get away with it on a 32 bit build because the size of int is the same as the size of a pointer.

另一方面,如果您将程序构建为64位程序,则警告实际上变得很相关,因为现在指针的宽度为64位,但是由于编译器假定 malloc 等,因此返回 int s(32位值),一切都搞砸了.

On the other hand if you build your program as 64 bit program, the warnings become really relevant, because now pointers are 64 bits wide, but as the compiler assumes that malloc etc. return ints (32 bit values), everything get messed up.

实际上,这些警告应视为错误.

在这里,您决定要构建32位还是64位:

Here you decide if you want a 32 or a 64 bit build:

my_lib.c 的此处添加 #include< stdlib.h> :

#include "my_lib.h"
#include <stdlib.h>   // <<<<<<<<<<<<<
#include <stdio.h>


// CREATE A MATRIX WITH N_ROWS AND N_COLUMNS AND INITIALIZE EACH VALUE AS 0
Matrix* make_matrix(int n_rows, int n_cols) {
  Matrix* matrix = malloc(sizeof(Matrix));
  ...

这篇关于“违反写权限";在函数内部使用malloc()之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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