为什么出现分段错误 [英] Why segmentation fault

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

问题描述

以下代码块出现分段错误.请帮忙.

Following block of code is giving segmentation fault.Please help.

 #include<stdio.h>
    int main(){
        int testcase,num;
        int i,j,*array;
        scanf("%d",&testcase);
        for(i=0;i<testcase;i++){
            scanf("%d",&num);
            for(j=0;j<num;j++){
                scanf("%d",(array+j));
            }
        }
        i=0;
        for(i=0;*(array+i)!='\0';i++){
            printf("%d",1);
        }
        }

推荐答案

Edit 2

想把它放在首位.

我只是注意到你的代码有点奇怪.当您读取数字时,您在 i 上有一个循环,然后在 j 内部有另一个循环 - 每次迭代您只是覆盖您已经读取的值.这很奇怪,我不确定你的初衷是什么.因此,尽管 segmentation fault 仍然是由于未分配的数组引起的,但我在此处编写的解决方案并不是正确的解决方案(在我理解您的意思之前,我不确定什么是正确的解决方案)要做)

I just noticed that your code is kind of weird. When you're reading the numbers, you have a loop over i, but then another loop over j inside - and each iteration you just overwrite the values you already read. This is weird, and I'm not sure what your original intent was. So although the segmentation fault is still caused because of unallocated array, the solution I wrote here isn't the correct one (and I'm not sure what would be the correct solution until I understand what you meant to do)

Edit2 结束

array 未初始化.

它是一个指向内存中某个地方的指针,但那个地方不是空闲的,所以当你在那里写时,你会写上重要的东西并导致分段错误.

It's a pointer pointing to a place in memory, but that place isn't free, So when you write there you write over important stuff and cause segmentation fault.

在您的情况下解决它的最佳方法是添加

The best way to solve it in your case is to add

array=malloc(sizeof(int)*testcase);

就在你阅读testcase的那一行之后,所以就在

just after the line where you read testcase, so just after

scanf("%d",&testcase);

此外,如果您这样做,最好在使用完该内存后释放该内存.所以在你的情况下添加

Also, if you do that, it's good practice to free that memory once you're done using it. So in your case add

free(array);

就在你完成打印整个数组之后

just after you're done printing the whole array

编辑刚刚注意到您有另一个错误 - 在您打印数组的循环中:

Edit Just noticed you have another bug - at the loop where you're printing the array:

for(i=0;*(array+i)!='\0';i++){

这很糟糕,因为您正在处理 array,它是一个整数数组,就像一个字符串.普通"数组不以 '\0' 结尾.此外 - '\0' 是一个 char,而 *(array+i) 是一个 int.

That is bad, bacause you're treating array, which is an array of ints, like it's a string. "normal" arrays don't end in '\0'. Moreover - '\0' is a char, and *(array+i) is an int.

for (i=0;i<testcase;i++){

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

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