Search code examples
cpointersmemoryrealloc

Easiest way to realloc


I was just curoius is what is the easiest way to realloc memory? On my faculty we've used this code to realloc memory (example):

if (dat = fopen(argv[1], "rb")) {
    do {
      p = fread(&art, sizeof(ARTIKAL), 1, dat);
      if (p) {
        if (n == c) niz = (ARTIKAL *)realloc(niz, (c *= 2) * sizeof(ARTIKAL));
        niz[n++] = art;
      }
    } while (p);
    fclose(dat);

I'm thinking about using rewind function but I'm not 100% sure how could I implement it.


Solution

  • Why would you need a rewind() function in this example?

    Your example seems to be fine, one thing that can be improved:

    if (dat = fopen(argv[1], "rb")) {
    do {
      p = fread(&art, sizeof(ARTIKAL), 1, dat);
      if (p) {
        if (n == c) 
        {
           ARTIKAL *tmp = (ARTIKAL *)realloc(niz, (c *= 2) * sizeof(ARTIKAL));
    
           if (tmp == NULL)
           {
             printf("Not enough memory!\n")
             return 0;
           }
           else
           {
             niz = tmp;
           }
    
        niz[n++] = art;
      }
    } while (p);
    fclose(dat);
    

    buy adding the above, your code is safer, since realloc returns NULL when it fails to allocate space, and you then loose your data.