简体   繁体   English

malloc和realloc分段错误

[英]malloc and realloc segmentation fault

I'm working on linux and using as compiller gcc. 我在linux上工作,并用作giller编译器。 I'm make some expriences with the functions malloc and realloc try to understand how it works. 我对malloc和realloc函数有一些了解,以了解其工作原理。 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; i从来没有初始化过,所以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. 您的代码还有其他一些改进,例如, 不要malloc的结果,在我看来,您不需要使用goto ,并且register关键字可能没有用。

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. 在while循环中,用户输入0后,它将存储在n ,您将cont递增,而while循环再次检查输入条件n != 0它失败了(因为n的值现在为0)并退出了循环而不将n值存储到a ,这就是为什么在输出的最后一位得到不确定的值的原因。

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. 当使用realloc时,不应将返回值直接存储到试图增加大小的指针变量中,因为realloc失败时返回NULL,最终会擦除内存缓冲区的句柄/地址。

    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++;
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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