【问题标题】:Problem with a function using realloc that seemingly worked 2 weeks ago使用 realloc 的函数出现问题,该函数在 2 周前似乎有效
【发布时间】:2021-08-16 13:25:44
【问题描述】:

所以,一个简单的搜索函数应该返回一个指向数组的指针,该数组的元素索引与 x 匹配,并与另一个指针 - *count 保持计数。根据编译器的不同,当我调用此函数或有关 realloc 将 void 转换为 int 的错误时,它会停止执行,其中一个也给了我一个分段错误......最令人困惑的部分是我在其他项目上有非常相似的函数并且它有效直到今天(我有截图证明它确实如此)并且没有被触及。

int *search(int arr[], int n, int x, int *count)
{
    int arrsize = 0;
    int *pointarr = malloc(sizeof(int));

    for (int i = 0; i < n -1; i++)
    {
        if (arr[i] == x)
        {
            arrsize++;
            pointarr = realloc(pointarr, sizeof(int) * arrsize);
            pointarr[arrsize - 1] = i;
        }
    }
    *count = arrsize;
    return pointarr;
}

我知道我的指针和内存分配从来都不是很好,但它确实有效......我迷路了。

int main()
{
    int x, n;
    int *tab; // it's later filled no problem as other, simpler function calls it with no problems
    int *tabindex;
    int *count = 0;  //I tried with both =0 and without
   
    //////

    tabindex = search(tab, n, x, count); //I tired with all stuff like &count *count etc etc if that's the problem but I don't think so
    for (int j = 0; j < *count; j++)
        printf("%d ", tabindex[j]);

【问题讨论】:

  • int *pointarr = malloc(sizeof(int)); --> int *pointarr = NULL;
  • "converting void to int" 嗯...确定这是一个正确的报价?
  • i &lt; n -1 嗯...为什么-1
  • 严格来说,您不应该在检查 NULL 之前将 realloc 返回的值保存在 pointarr 中。在任何情况下,您都应该在pointarr[arrsize - 1] = i; 之前检查NULL。也就是说,我认为这不是真正的问题
  • 这只是检查我是否没有尝试访问我不应该访问的东西的遗物,它现在不会影响代码,因为它在我的电脑上没有 -1。

标签: c memory segmentation-fault


【解决方案1】:

这是因为您使用 C++ 编译器编译 C 代码。如果您开始使用 Visual Studio(这是最可能的选项),您需要将项目选项更改为编译为 C 语言。

【讨论】:

  • 我现在正在使用 Visual Studio 代码,但在设置中没有任何类似的返回,除了我在右下角将它设置为 C。自从上次相同的东西工作以来,我也没有改变任何东西,也没有用 C++ 编写代码
  • @keiji12 但信息很明确。你用的是什么编译器
  • 我正在使用 gcc,很抱歉,我对这类东西不太擅长,我刚刚安装了一段时间,并在工作室代码的一些扩展上进行了一个学期的实验室和之后什么都没改变
猜你喜欢
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-11
  • 2012-12-09
  • 2020-09-19
相关资源
最近更新 更多