我正在尝试使用 malloc 将内存分配给我的 int 指针。我遇到分段错误,当我尝试使用 gdb 调试它时,我得到以下输出:
程序接收信号SIGSEGV,分段错误。 0x00007ffff7a97f90 in __GI___libc_realloc (oldmem=0x7fffffffdfd0, bytes=1) at malloc.c:3015 3015 malloc.c:没有这样的文件或目录。
代码如下:
int stringAllocation(char **destination){
char c=1, *temp;
int ctr=0;
int num_of_char=0;
while(c!='n'){
c=getc(stdin);
num_of_char+=1;
temp=realloc(*destination, sizeof(char)*num_of_char);
if(temp)
*destination=temp;
else{
printf("String allocation failure.");
return -1;
}
*(*destination+ctr)=c;
ctr++;
}
if((*destination)[ctr-1]=='n')
(*destination)[ctr-1]=' ';
}
main(void){
char *temp_course;
int temp_sem;
int temp_acad_year;
int valid=0;
char dummy;
int ctr;
while(valid==0){
dummy=0;
while(dummy!='n')
dummy=getc(stdin);
printf("nGetting course!n");
printf("nCourse code: ");
stringAllocation(&temp_course);
printf("Semester: ");
scanf("%d", &temp_sem);
if(temp_sem<1||temp_sem>3){
valid=0;
continue;
}
else
valid=1;
printf("Academic year: ");
scanf("%d", &temp_acad_year);
if(temp_acad_year<1908||temp_acad_year>2015){
valid=0;
continue;
}
else
valid=1
}
int numstud;
int *studnum;
valid=0;
while(valid==0){
printf("Input number of students: ");
scanf("%d", &numstud);
if(numstud>=5&&numstud<=15)
valid=1;
}
studnum=(int*)calloc(numstud,sizeof(int));
}
}
temp_course未初始化。 因此,当在调用重新分配时使用其现有值时,代码会崩溃。 将其初始化为 NULL。