简体   繁体   中英

malloc and realloc segmentation fault

I'm working on linux and using as compiller gcc. I'm make some expriences with the functions malloc and realloc try to understand how it works. But when I execute the program give me segmentation fault. next my code:

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

 int main(){
  register int cont=1;
  int i,n,*a;
  a=(int*)malloc(sizeof(int));
  scanf("%d",&n);
  while(n!=0){
   if(a!=NULL)
    a=(int*)realloc(a,cont*sizeof(int));
   else 
    goto exit;
   a[i]=n;
   scanf("%d",&n);
   cont++;
   i++;
 }

 for(i=0;i<cont;i++)
  printf("%d\n",a[i]);
 free(a);
 return 0;

 exit: printf("No memory\n");
 free(a);
 return -1;



}

Why this don't work and whats wrong with my code?

i is never initialized, so a[i]=n; probably causes the segmentation fault. Change it to:

int i = 0;

There are some other improvement can be done to your code, eg, don't cast the result of malloc , your use of goto doesn't look necessary in my opinion, and register keyword is probably useless.

In the while loop, after the user enters 0 , it is stored in n , you incremented the cont and when the while loop again checked the entry condition n != 0 it failed (because the value of n now is 0) and exited the loop without storing the n value to a , that is why you are getting the indeterminate value in the last place of your output.

When you are using realloc, you should not store the return value directly to the pointer variable which you are trying to increase the size, since realloc return NULL on failure, you end up erasing the handle/address to the memory buffer.

    register int cont = 1;
    int i = 0,n,*a;
    int *temp;
    a = (int*)malloc(sizeof(int));
    if(a == NULL) goto exit;
    while(1){
       scanf("%d", &n);
       temp = (int*)realloc(a, cont * sizeof(int));
       if(temp == NULL)
         goto exit;
       else
         a = temp;
       a[i++] = n;
       if(n == 0) // put the condition here if u want to store 0
         break;  
       else
         cont++;
     }

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