程序结束后出现分段错误 [英] Segmentation fault after program finishes

查看:134
本文介绍了程序结束后出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个家庭作业,而且我相对比较新。我必须为一个整数数组创建一个初始化器。



给出的声明我的教授给我的是:

pre $ typedef int set_t; //不能被修改
...
void init(set_t * thing,int N){} //不能被修改
...
int main (){
set_t a; //不能改变
init(& a,10); //不能改变
返回0;

$



初始化器应该在数组<$ c $中分配空间N个元素c> set_t a;



以下是我的初始化程序代码:

 void init(set_t * thing,int N){

* thing = *(set_t *)malloc(sizeof(set_t)* N); (int i = 0; i< N; i = i + 1){
*(thing + i)= i;


}
return;
}

所有的编译都很好,但是当我运行它时,整个程序运行,然后运行我得到了一个分段错误(在我的代码副本中,我有一堆运行的打印语句,因此我知道它在整个程序中运行,然后才得到seg错误)。

如何解决这个错误的任何方向将不胜感激!

解决方案

教授意识到他已经做了分配中的错误并修复它。已将 set_t a 更改为 set_a * a



感谢您的所有帮助(希望我不会造成太多的麻烦!)


I'm working on a homework assignment and I'm relatively new to C. I have to create an initializer for an array of integers.

The declarations given to me by my professor are:

typedef int set_t;    // Can't be altered
...
void init(set_t *thing, int N) {}    // Can't be altered
...
int main() {
    set_t a;         // Can't be altered
    init(&a, 10);    // Can't be altered
    return 0;
}

The initializer is supposed to allocate space a N elements in array set_t a;

Here is the code for my initializer:

void init(set_t *thing, int N) {

    *thing = *(set_t *)malloc(sizeof(set_t)*N);

    for (int i = 0; i < N; i = i + 1) {
        *(thing+i) = i;
    }
    return;
}

Everything compiles just fine but when I run it, the entire program runs and then I get a segmentation fault (In my copy of this code I have a bunch of print statements that run, hence how I know it runs through the entire program before I get the seg fault).

Any direction on how to fix this error would be greatly appreciated!

解决方案

Professor realized that he had made an error in the assignment and fixed it. Changed set_t a to set_a *a.

Thanks for all your help (hope I didn't cause too many headaches!

这篇关于程序结束后出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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