int指针函数seg在c中有大数字的错误

时间:2016-06-09 06:14:33

标签: c pointers

int     *rrange(int start, int end);

我被问到,编写一个函数并用malloc分配一个整数数组,用连续填充它 从结束开始到结束的值(包括开始和结束!),然后 返回指向数组第一个值的指针。这些函数适用于小数字,当用大数字测试时,我得到seg fault。而且我认为seg fault因为达到int的限制而得到/*- With (1, 3) you will return an array containing 3, 2 and 1 - With (-1, 2) you will return an array containing 2, 1, 0 and -1. - With (0, 0) you will return an array containing 0. - With (0, -3) you will return an array containing -3, -2, -1 and 0.*/ #include <stdlib.h> int *rrange(int start, int end) { int *range; int i; i = 0; range = (int *)malloc(sizeof(int *)); if (end <= start) { while (end <= start) range[i++] = end++; } else { while (end >= start) range[i++] = end--; } return (range); } = Test 1 =================================================== $> ./pw53y11cbachacu14eue5cab $> diff -U 3 user_output_test1 test1.output | cat -e Diff OK :D = Test 2 =================================================== $> ./o1jrm4t3vqengizvj1tlwab4 "21" "2313" "12" $> diff -U 3 user_output_test2 test2.output | cat -e Diff OK :D = Test 3 =================================================== $> ./usl3i1tc1xv9tr1gs9n5x5vr "2147483647" "2147483640" "7" $> diff -U 3 user_output_test3 test3.output | cat -e --- user_output_test3 2016-06-08 16:26:16.000000000 +0200$ +++ test3.output 2016-06-08 16:26:16.000000000 +0200$ @@ -1,8 +1,8 @@$ -0$ -0$ -0$ -0$ -0$ -0$ -0$ +2147483640$ +2147483641$ +2147483642$ +2147483643$ +2147483644$ +2147483645$ +2147483646$ $ Diff KO :( Grade: 0 = Final grade: 0 =============================================================== 。我该如何解决这个问题?。

/*function to parse the HTML*/
private void parseHTML(String szHTML){
    Document doc = Jsoup.parse(szHTML);

    Elements arrEle = doc.select("section");

    for(Element child: arrEle){
        printSectionDetails(child);
    }
}

/*function to print section details : prints direct child header name and img src of the section node */
private void printSectionDetails(Element section){
    Elements arrChildren = section.children();
    for(Element child : arrChildren){
        if(isHeader(child.tagName())){
            System.out.println(child.text());
        }

        if(child.tagName().equals("div")){
            Elements children = child.children();

            for(Element grandchild : children){
                if(grandchild.tagName().equals("figure")){
                    Elements arrImgs = grandchild.select("img");
                    for(Element img : arrImgs){
                        System.out.println(img.attr("src"));
                    }
                }
            }
        }
    }
}

/*checks whether the tag is a header*/
private boolean isHeader(String tagName) {
    if("h1".equalsIgnoreCase(tagName) || "h2".equalsIgnoreCase(tagName) || "h3".equalsIgnoreCase(tagName) || "h4".equalsIgnoreCase(tagName) || "h5".equalsIgnoreCase(tagName) || "h1".equalsIgnoreCase(tagName) || "h6".equalsIgnoreCase(tagName)){
        return true;
    }

    return false;
}

5 个答案:

答案 0 :(得分:4)

您的问题来自malloc

而不是

range = (int *)malloc(sizeof(int *));

你应该写:

range = malloc(nb_of_integer_in_range * sizeof (int));

由您来计算nb_of_integer_in_range,例如:

int nb_of_integer_in_range;
if (end > start)
{
    nb_of_integer_in_range = end - start + 1;
}
else ...

答案 1 :(得分:1)

由于错误的内存分配而发生了段错误

range = (int *)malloc(sizeof(int *));

这会分配一个整数指针大小的内存。但要为数字分配内存,您需要以这种方式为每个数字创建所需的内存量:

range = malloc(no_of_elements*sizeof(int));
  

注意:使用n作为全局变量,以便您可以知道其大小   甚至在函数()中打印数组

我修改了你的功能

int *rrange(int start, int end)
{
    int *range;
    int i;

    if(start>end)
        return rrange(end,start); //so that start is always <end

    n=end-start+1; // n globally declared 

    range=malloc(n*sizeof(int)); //casting is not required
    if(range==NULL)
    {// check if memory was successfully allocated if not exit
        printf("fail");
            exit(1);
    }
    for(i=0;i<n;i++,start++)
    {
        range[i]=start;
    }

    return range;
}

你现在可以把你的主要写成:

int main()
{
    int x,y,*r,i;
    scanf("%d%d",&x,&y);
    r=rrange(x,y);
    for(i=0;i<n;i++)
    {
        printf("%d,",r[i]);
    }
    return 0;
}

答案 2 :(得分:0)

我很惊讶这适用于任何大于2的范围。你正在分配8B的存储空间(假设你运行的是64b机器),或者通常是指针大小。 你想要的是一个malloc表达式,它取决于startend之间的差异(给你数组大小) sizeof(int)(给你数组) 元素大小)。

不相关的注意事项:确保在停止使用阵列时释放存储空间,否则您的程序将像筛子一样泄漏。

答案 3 :(得分:0)

malloc的论点应为number_of_integers * sizeof(int)。例如,number_of_integers的值可以计算为abs(start-end)+1,但我会在malloc - if内执行public ValueFrequency(ValueFrequency<T> valueFrequency) { if (valueFrequency.Value is ICloneable) Value = (T)((ICloneable)valueFrequency.Value).Clone(); else Value = valueFrequency.Value; _frequency = valueFrequency.Frequency; } - 开头和结尾之间的关系众所周知。

答案 4 :(得分:0)

以下代码:

  1. 干净地编译
  2. 执行所需的功能
  3. 正确处理错误情况
  4. 如果start大于end,则
  5. 可能无效,但这不属于条件
  6. 现在是代码:

    /*- With (1, 3) you will return an array containing 3, 2 and 1
    - With (-1, 2) you will return an array containing 2, 1, 0 and -1.
    - With (0, 0) you will return an array containing 0.
    - With (0, -3) you will return an array containing -3, -2, -1 and 0.*/
    
    #include <stdlib.h> // exit(), EXIT_FAILURE
    #include <stdio.h>  // perror()
    #include <math.h>   // abs()
    
    int *rrange(int start, int end)
    {
        int *range = NULL;
    
        if( NULL == (range = malloc( sizeof(int) *((size_t)abs(end - start) +1) ) ) )
        { // then malloc failed
            perror( "malloc failed" );
            exit( EXIT_FAILURE );
        }
    
        for( int index = 0; index < abs(end-start)+1; index++ )
        {
            range[ index ] = start+index;
        }
    
        return (range);
    } // end function: rrange