我对编程相对较新(几个月),正在尝试一些 USACO 问题。 当我提交程序时,它是这样说的:
Run 1: Execution error: Your program (`palsquare') exited with signal #11 (segmentation violation [maybe caused by accessing memory out of bounds, array indexing out of bounds, using a bad pointer (failed open(), failed malloc), or going over the maximum specified memory limit]). The program ran for 0.005 CPU seconds before the signal. It used 2168 KB of memory.
我找不到任何取消引用的空指针,我最初认为这是问题所在。
这是我的代码(我用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;
}
最佳答案
使用 square = ""
,您将更改变量 square
的值以指向空字符串。
由于此变量是函数 convert
中的本地变量,因此更改它在函数外部不会产生任何影响。
如果要将指向的数据设置为空字符串,请使用square[0] = '\0'
。
顺便说一句,即使它确实在函数外以某种方式产生影响(例如,如果您使用全局变量而不是局部变量),那么它不仅不能解决问题,而且还会使事情变得更糟更糟糕的是:
- 此变量将指向一个字符串,分配在具有只读访问权限的内存段中。
- 此变量将指向一个字符数组,在内存中分配为单个字符的大小。
由于这些事实中的每一个分别,任何试图更改此变量所指向的内存地址及其周围内容的尝试很可能会在运行时产生内存访问冲突。
关于c - 段错误--信号 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26521401/