0

I would like to resize the array when it reaches its max capacity. But error came up after i do ./a.out Please help me...

Error: a.out: malloc.c:3574: mremap_chunk: Assertion `((size + offset) & (mp_.pagesize-1)) == 0' failed.

code:

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


int main(void)
{
  int cap=5;
  int *arr = malloc(cap*sizeof(int));
  FILE *f;

  if((f=fopen("/home/file.txt","r"))==NULL)
    printf("You cannot open");  

  while(fscanf(f, "%d", arr++)!=EOF)
  {
    index++;
    if(index==cap-1)
      arr = realloc(arr, (cap +=1) * sizeof(int));
  } 

  return 0;
}

2 Answers 2

5

You have arr++ in your loop condition. That means arr doesn't point to the start of the allocated memory anymore when you call realloc(). That's going to end up with the error you're seeing.

Also:

  1. Programming safety note:

    Don't call realloc() in the form:

    foo = realloc(foo, bar);
    

    If an error occurs, foo will be set to NULL and you'll leak the original allocation.

  2. Nonidiomatic code note:

    (cap +=1) * sizeof(int)
    

    is a bit weird. Why not ++cap * sizeof(int)? Or better yet, do it on two lines rather than cramming it all into one.

Sign up to request clarification or add additional context in comments.

7 Comments

So the solution will be using a pointer to point to the arr and then read from the pointer right?
Just don't lose the pointer to the beginning of your allocation. Make a copy and use that when calling realloc(), for example.
I did the following: int *y = arr; while(fscanf(f, "%d", y++)!=EOF) so now i have a new pointer do the work, and arr is not change it original location. But instead i got a segmentation error :(
When you call realloc(), the base pointer to the array (arr) might change. You'll need to adjust y to match if that happens.
But how do i ensure that y is not reading from the beginning again after i adjust the y?
|
0

You need to perform the realloc on the same address received fromm malloc, but you increase arr in while(fscanf(f, "%d", arr++)!=EOF)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.