简体   繁体   中英

Using realloc to extend memory space taken with malloc?

As a school assigment I need to create memory block with malloc and when its full it should extend itself with realloc.This will continue in a infnite loop.But I am getting segmantation fault error and I think the mistake is in realloc so can anyone tell me what I am doing wrong ?

#include "stdio.h"
#include "stdlib.h"
int main()
{
  int boyut=5;
  int* dizi;
  dizi=(int *)malloc((boyut*sizeof(int)));
  int b=0;
while(b<1)  
    {   
if(*dizi<boyut){                
 scanf("%d",dizi);
dizi++;                
 }
else if(boyut=*dizi)         
 {
    printf("boyut yetersiz");
    dizi = (int*) realloc (dizi,2*sizeof(int));
    boyut=*dizi*2;                  
 }  
}
  return 0;
}

Edited according to answers its extending the malloc area by *2.

int main()
{
  int boyut=2;
  int* dizi;
  int* dizi1;
  int n;
  dizi=(int *)malloc((boyut*sizeof(int)));
  int b=0;
  int i;
while(b<1)  
    { 

if(i<boyut){           

  for(i=0;i<boyut;i++){ 
    printf("\nDeğer Girin:");
 scanf("%d",dizi);
 }
 }
else if(boyut=i)         
 {

    boyut=boyut*2; 
    printf("\nBoyut yetersiz yeni boyutu %d yapıyoruz",boyut);
    dizi1 = (int*) realloc (dizi,boyut*sizeof(int));
    dizi=dizi1;


 }

}
  return 0;
}

Correct answer thanks for those who have same questions can use it.

You actually reallocate to less than before the reallocation. First you allocate space for 5 ( boyut ) integers, then you reallocate space for only two integers. You need to increase boyut and reallocate with that as a multiplier.

You also need to remember that realloc can fail, and in that case will set dizi to NULL , making you both dereference a NULL pointer and loose the original pointer so you can't free it.

Also, don't cast the result of malloc (or realloc for that matter) .


The real problem, as pointed out by BLUEPIXY, is because of undefined behavior . For realloc to work it needs to be passed the original pointer. You no longer have it after you do dizi++ .

Also, when you allocate memory, the contents is uninitialized , meaning it will contain seemingly random data. So doing *dizi before you initialize that data will also result in undefined behavior. You might want to use eg calloc instead.

The second argument to realloc is the total size of the allocation requested, not the amount by which it should grow. You should keep track of the size of the allocation:

size_t size = some_size;
void *ptr = malloc(some_size);
// check for errors

while (some_condition) {
    size += some_increment;
    void *newptr = realloc(size);
    // check for errors
    ptr = newptr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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