【发布时间】:2026-01-19 03:50:01
【问题描述】:
我对编程比较陌生(几个月)并且正在尝试一些 USACO 问题。 当我提交我的程序时,它是这样说的:
运行 1:执行错误:您的程序 (`palsquare') 以 信号 #11(分段违规[可能是由于访问 内存超出范围,数组索引超出范围,使用错误 指针(open() 失败,malloc 失败),或超过最大值 指定的内存限制])。程序运行了 0.005 CPU 秒 在信号之前。它使用了 2168 KB 的内存。
我找不到任何取消引用的空指针,我最初认为这是问题所在。
这是我的代码(我用 C 语言编写的)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <math.h>
int ispal( char *square )
{
char *temp;
temp = square + strlen( square ) - 1;
for( temp = square + strlen( square ) - 1; square < temp; square++, temp-- )
{
if( *square != *temp )
return 0;
}
return 1;
}
void convert( char *square, int n, int base )
{
int len;
if( n == 0 )
{
square = "";
return;
}
convert( square, n / base, base );
len = strlen( square );
square[len] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n % base];
square[len + 1] = '\0';
}
int main()
{
char square[100];
char temp[100];
int i, base;
FILE *fin, *fout;
fin = fopen( "palsquare.in", "r" );
fout = fopen( "palsquare.out", "w" );
fscanf( fin, "%d", &base );
for( i = 1; i <= 300; i++ )
{
convert( square, i * i, base );
if( ispal( square ) )
{
convert( temp, i, base );
fprintf( fout, "%s %s\n", temp, square );
}
}
return 0;
}
【问题讨论】:
-
程序是否在您自己的机器上运行?您是否尝试过 valgrind 或调试器?
-
不,程序崩溃了,我不知道如何使用 Dev C++ 的调试器(再说一次,我很新:P)
-
使用
strcpy()分配字符串,而不是square = ""。 -
@WhozCraig 因为他在分配后立即返回,所以没有从那时起
-
@Barmar 呃。没有看到回报。谢谢你让我诚实。和
*square = 0;似乎比使用strcpy更少矫枉过正。
标签: c segmentation-fault