如何知道堆溢出点?

问题描述 投票:0回答:1

我正在尝试编写一个程序来确定给定范围内的所有回文。 我的程序调用一个函数(位数),该函数返回整数的大小(即 400 将是 3,因为它有 3 位数字),然后(另一个 - Splitis)返回一个数字位置(即,对于 400,3 将返回4,因为这是第三个数字,然后程序将独立值存储在指针数组中(例如,100 将存储为 1,0,0)。指针,一个代表总数,然后一个代表基于数字大小的每个元素。出于某种奇怪的原因,当我的数组超过大约 8000 个指针时,我会遇到分段错误,因为它总是像钟表一样失败。当我使 malloc 变小时,它似乎工作得更好,我假设我以某种方式溢出了堆,我试图找出为什么我不断出现段错误?代码如下。

#include <stdio.h>
#include <stdlib.h>
#include "external file location"

int main(void)
{
double testsize=0;
int count=0;
int **currentarray;
int *innerarray=NULL;
size_t sizeofarray=9000;
currentarray=(int **)malloc(sizeof(int)*sizeofarray);
for(int A=0; A<sizeofarray; A++)
{
    size_t b=numberofdigits(&A);
    *(currentarray+A)=(int *)malloc(sizeof(int)*b*1);
    if(currentarray==NULL)
    {
    perror("malloc failed");
    }
    int c=0;
    for(c=b; c>=1; c--)
    {
    *(*(currentarray+A)+c)=SplitIs(A, c);       
    }
    if((*(*(currentarray+A)+1)==*(*(currentarray+A)+b)) && (b>1))
    {
    fprintf(stdout, "%d)", count++);
        for(int c=b; c>=1; c--)
        {
        fprintf(stdout, "%d", *(*(currentarray+A)+c));
        }
    putchar('\n');
    }
}
for(int i=0;i<sizeofarray; i++)
{
//free((currentarray+i)); //I haven't figured out how to free it yet as the pointer is contained in the above block.  Commented out for now.  A future question.
}
}
arrays pointers malloc heap-memory dynamic-memory-allocation
1个回答
0
投票

我已经解决了上面提到的问题,并且您的代码似乎可以正常工作,没有错误。 请注意,我提供了

numberofdigits
SplitIs
的版本,因为您没有提供它们。

这在 C++ 中会更可靠。

#include <stdio.h>
#include <stdlib.h>

int numberofdigits( int * x )
{
    int c = 1;
    int d = 0;
    while( *x > c )
    {
        d += 1;
        c *= 10;
    }
    return d;
}

int SplitIs( int a, int c )
{
    while( --c )
        a /= 10;
    return a % 10;
}

int main(void)
{
    int count=0;
    int **currentarray;
    int *innerarray=NULL;
    size_t sizeofarray=9000;
    currentarray=(int **)malloc(sizeof(int*)*sizeofarray);
    for(int A=0; A<sizeofarray; A++)
    {
        int b=numberofdigits(&A);
        currentarray[A]=(int *)malloc(sizeof(int)*b+1);
        if(currentarray==NULL)
        {
            perror("malloc failed");
        }
        int c=0;
        for(c=b; c>=1; c--)
        {
            currentarray[A][c]=SplitIs(A, c);       
        }
        if((currentarray[A][1]==currentarray[A][b]) && (b>1))
        {
            fprintf(stdout, "%d)", count++);
            for(int c=b; c>=1; c--)
            {
                fprintf(stdout, "%d", currentarray[A][c]);
            }
            putchar('\n');
        }
    }
    for(int i=0;i<sizeofarray; i++)
    {
        free(currentarray[i]);
    }
    free(currentarray);
}
© www.soinside.com 2019 - 2024. All rights reserved.