简体   繁体   English

释放大量指针时的分段错误

[英]Segmentation fault when free large array of pointers

My code runs with no errors on small files. 我的代码在小文件上运行没有错误。 But I get segmfault on large inputs (millions line). 但是我在大型输入(百万行)上遇到了段错误。 Please see some of the code below: 请查看下面的一些代码:

element* unionFind(void *data)
{
    element *retVal = NULL;
    retVal = (element *)malloc(sizeof(element));
    retVal->data = data;
    retVal->rank = 0;
    retVal->leader = retVal;
    return retVal;
}

Main: 主要:
... ...

int main (int argc, char* argv[])
{   
char str[2048]; 
char* v_S = NULL; 
struct set *s_v = NULL;

* count number of lines in input *计算输入中的行数

long *v_L = (long *)malloc(sizeof(long)*ct_lines);
element **v = malloc(sizeof(element)*ct_lines) ;

while(fgets(str,sizeof(str),fp) != NULL)
{
     v_S = strtok(str,":");        

     v_L[i] = atol(v_S);
         v[i] = unionFind(&v_L[i]);
     s_v = add_vertex(v_L[i], v[i]);

     i++;
}

fclose(fp);

for (i = 0; i < ct_lines; i++) //Here segfault
    {
    free(v[i]); v[i] = NULL;
    }

free(v); v = NULL;
free(v_L); v_L = NULL;

}

after each malloc you should check whether malloc has returned NULL( which means memory could not be allocated as heap is full). 在每个malloc之后,您应该检查malloc是否返回了NULL(这意味着由于堆已满,无法分配内存)。 If it returns NULL, generally error message is printed. 如果返回NULL,通常会显示错误消息。 And if still you want to allocate memory you will have to retry after freeing up some already allocated memory. 如果仍然要分配内存,则必须在释放一些已经分配的内存后重试。

As your program fails for large files, no need of reading code in detail, it must be failing since its running out of free memory and malloc is returning NULL and then you are trying to save structure elements at NULL address in top function findUnion. 由于您的程序针对大型文件而失败,无需详细阅读代码,因此它一定会失败,因为它的可用内存不足,并且malloc返回NULL,然后您尝试将结构元素保存在顶级函数findUnion中的NULL地址处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM