为什么这个代码中的sagemention错误? [英] Why is the sagemention fault in this code ?

查看:94
本文介绍了为什么这个代码中的sagemention错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int test_polygon(struct Polygon* poly, struct Pointf target)    //  mathematical algorithm to know whether the point is inside the polygon.
{
    int  i, j, c=0;           // new variables will be used in the next for loop.


    for (i =0,j=poly->nvert-1 ; i < poly->nvert ; j = i++)       // for (i=0,j=Number of vertices-1 ; i < Number of vertices ; j=i++)
    {
        if ((( poly->p[i].y > target.y) != (poly->p[j].y > target.y)) &&            //poly.p[i].y is y-coordinate of the polygon's vertices.
                (target.x < (poly->p[j].x - poly->p[i].x) * (target.y - poly->p[i].y) /     //poly.p[i].x is x-coordinate of the polygon's vertices.
                 (poly->p[j].y - poly->p[i].y) + poly->p[i].x))
            c = !c;
    }
    return c;
}





我的尝试:



i将结构更改为指针,但我有相同的sagemention错误。



What I have tried:

i changed the structure to pointers , but i have the same sagemention fault.

推荐答案

在不知道<$ c $的情况下无法回答c> Polygon 结构以及如何初始化传递的结构。



可能的来源可能是


  • poly 参数是无效指针

  • poly-> p 是无效指针

  • poly-> nvert 是< = 0

  • poly-> p 是一个数组,其大小小于 poly-> nvert

That can't be answered without knowing the Polygon structure and how the passed structure is initialised.

Possible sources may be

  • The poly parameter is an invalid pointer
  • poly->p is an invalid pointer
  • poly->nvert is <= 0
  • poly->p is an array which size is less than poly->nvert
/* NOTE: NDEBUG must not be defined to execute assert statements */
#include <assert.h>

int test_polygon(struct Polygon* poly, struct Pointf target)
{
    assert(poly != NULL);
    assert(poly->p != NULL);
    assert(poly->nvert > 0);
    /* EDIT: After knowing the struct Polygon uses a fixed size p array */
    assert(poly->nvert < sizeof(poly->p) / sizeof(poly->p[0]));
    
    /* ... */
}


指数 i j 似乎保持在 poly-> nvert 给出的限制范围内。因此,我能看到的唯一可能的错误原因是......



poly 未指向有效的Polygon对象(未初始化的变量,已删除的对象,......)



点数组 p 未正确分配(太短,即少于 nvert 项目)。



也许您发布一些代码,显示如何调用 test_polygon ,特别是传递哪些参数 - 最好是失败的调用分段错误。
Indices i and j appear to remain within the limits given by poly->nvert. Therefore, the only possible reason for a fault I can see is that...

either poly isn't pointing to a valid Polygon object (un-initialized variable, deleted object, ...)

or point array p isn't correctly allocated (too short, i.e. fewer than nvert items).

Perhaps you post some code showing how test_polygon is called, in particular which parameters are passed -- preferably the call that fails with a segmentation fault.


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

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