c - Realloc fails to dynamically grow a 1 to over a million elements -


reading 2 column text file , storing long int values array reallocated dynamically, fails when array grows on 200 thousand memory reallocations.

    long int load_list_unklen(long int (**ptr), file *infname)     {   long int row =0;         char buf[64];         while (fgets (buf, sizeof(buf), infname)) {             // m defined = 2             *ptr = (long int *)realloc(*ptr, m * row+1 * sizeof(ptr));             if(!ptr) {                 perror("out of memory");                 free(ptr);                 exit( 1); }             sscanf(buf, "%ld\t%ld", &(*ptr)[row*2],&(*ptr)[row*2+1]);             row += 1;         }         if (ferror(infname)) {             fprintf(stderr,"oops, error reading stdin\n");             abort();         }         return  row;     } 

notice buf gets string has 2 numbers separated tab. code fails tries load file on 2mil lines , row increments stop around 221181, wonder if there limit realloc chokes? should calling realloc differently?

here how call function:

long int *act_nei = (long int *)malloc(m * sizeof (act_nei) ); const long int sz  = load_list_unklen(&act_nei, fp); 

using code post realloc memory slots, example large input files.
realloc , sscanf functionrealloc , scanf

you corrupting malloc ring writing beyond allocated space. there missing () , wrong sizeof. try:

*ptr = (long int *)realloc(*ptr, m * (row+1) * sizeof(**ptr));


Comments