c - 段错误--信号 11

标签 c segmentation-fault

我对编程相对较新(几个月),正在尝试一些 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'

<小时/>

顺便说一句,即使它确实在函数外以某种方式产生影响(例如,如果您使用全局变量而不是局部变量),那么它不仅不能解决问题,而且还会使事情变得更糟更糟糕的是:

  1. 此变量将指向一个字符串,分配在具有只读访问权限的内存段中。
  2. 此变量将指向一个字符数组,在内存中分配为单个字符的大小。

由于这些事实中的每一个分别,任何试图更改此变量所指向的内存地址及其周围内容的尝试很可能会在运行时产生内存访问冲突。

关于c - 段错误--信号 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26521401/

相关文章:

c - 运行到在线编译器但在终端上出现段错误(Ubuntu)

c - 不断收到堆栈粉碎错误

c - C指针的大小取决于?

ruby-on-rails - 运行配置文件测试时出现 Ruby 段错误

分配内存时代码导致段错误或释放内存时中止程序

将数据复制/扫描/读取到未初始化的指针时崩溃或 "segmentation fault"

c - 我是 C 新手,我正在尝试学习使用结构,我的 unix 应用程序无法运行并显示 EXC_BAD_ACCES。帮助!

c - C中的信号处理——中断中的中断

c - 如何从堆栈中删除质数

c - scanf 使程序崩溃并比较字符串 C