我试图在HackerRank论坛上解决一个问题,但总是得到内存分配错误。 试图修复这个问题,但最后经过大量的爆炸后,失败了:( 请帮帮我这里有什么问题。(提前致谢) 问题链接: Hackerrank
int main(){
int testcases;
long N,*segment,*range,max,*temp,*ptr,k,y1,y2,count;
scanf("%d",&testcases);
for(int t=1;t<=testcases;t++){
max=0;
scanf("%ld",&N);
segment=malloc(sizeof(long)*N*2);
temp=segment;
for(long i=0;i<N*2;i++){
scanf("%ld",(temp+i));
if(*(temp+i)>max)
max=*(temp+i);
}
range=malloc(sizeof(long));
memset(range,0,sizeof(long)*max);
ptr=range;
k=0;
while(k<(N*2-1)) {
for(long a=*(temp+k);a<=*(temp+k+1);a++){
ptr[a]=ptr[a]+1;
}
k=k+2;
}
y1=0,y2=0;
ptr=range;
for(long i=0;i<max;i++){
if(ptr[i]>y2){
y2=y1;
y1=ptr[i];
}
}
count=0;
temp=segment;
for(long i=0;i<(N*2-1);i+=2 ){
if((y1>=(*(temp+i))&&y1<=(*(temp+i+1))) || y2>=(*(temp+i))&&y2>=(*(temp+i+1)))
count=count+1;
}
printf("Case %d:%ld\n",t,count);
free(segment);
free(range);
}
return 0;}
错误:
solution: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
答案 0 :(得分:2)
scanf("%ld",&N);
segment=(long *)malloc(sizeof(long)*2);
应该是
scanf("%ld",&N);
segment=malloc(sizeof(long)*N*2); /* You forget N (and don't cast malloc)*/
和
for(long i=0;i<(N*2-1);i+2 ){
应该是
for(long i=0;i<(N*2-1);i+=2 ){
在调试器中运行代码:
Program received signal SIGSEGV, Segmentation fault.
0x00000000004007f0 in main () at demo.c:28
28 ptr[a]=ptr[a]+1;
您正在以下区块中访问其范围之外的ptr
:
while(k<(N*2-1)) {
for(long a=*(ptr+k);a<=*(ptr+k+1);a++){
ptr[a]=ptr[a]+1;
}
k=k+2;
}