c - 段错误 SEGV_ACCERR - 对象的无效权限

标签 c unix gcc segmentation-fault

我已经编写了一个 C 代码来使用交换逻辑洗牌一副 52 张牌。该代码生成一个介于 0 到 53 之间的随机数(52 和 53 被省略),然后将其与数组中的第 i 个索引交换。代码如下。

我的问题: 当我在调用 swap() 函数之前注释掉 display() 函数调用时,程序会抛出一个段错误。但是当我取消注释并在调用 swap() 函数之前调用显示函数时,程序工作正常并且我得到了所需的输出。我不知道为什么会这样。

主要功能:

int main()
{
char deck[] = {'2','3','4','5','6','7','8','9','0','A','J','K','Q'};
char suit[] = {'D','H','S','C'};

char **array,**array1;
array = malloc(sizeof(char *)*52);
array1= array;

srand(time(NULL));

for(int i=0;i<=12;i++)
{
        for(int j=0;j<=3;j++)
        {
                if((*array = malloc(sizeof(char)*2))!=NULL)
                {
                        sprintf(*array,"%c%c",deck[i],suit[j]);
                        *array++;
                }
        }
}

//display(array1); // when i comment this line, the program throws segfault. when i uncomment it the program runs fine. 
swap(array1);
display(array1);
free_array(array1);
return 0;
}

这是交换和显示的其他功能。

void display(char **array)
{
char **temp;
temp = array;

for(int i=0;i<=51;i++)
{
        printf("temp [%s]\n",*temp);
        *temp++;
}

return;
}

void swap(char **array)
{
char **temp;
int x;
temp = array;
char *temp1;

for(int i=0;i<=51;i++)
{
        x = rand()%53;
        if(x == 53 || x == 52)
                continue;

        memcpy(temp1,temp[i],2);   // program segfaults here. 
        memcpy(temp[i],temp[x],2);
        memcpy(temp[x],temp1,2);
}
return;
}

最佳答案

在交换函数中 -

您正在使用 temp1 而未对其进行初始化。

void swap(char **array)
{
  char **temp;
  int x;
  temp = array;
  char temp1[ 2 ];

  for(int i=0;i<=51;i++)
  {
        x = rand()%53;
        if(x == 53 || x == 52)
                continue;

        // need to multiply the indexes by 2
        // allowing for the suit and deck
        memcpy(temp1,temp[ i  ],2);   // program segfaults here. 
        memcpy(temp[ i  ],temp[ x  ],2);
        memcpy(temp[ x  ],temp1,2);
  }
}

上面显示 temp1 正确初始化。

我还没有检查你的函数的其余部分,但这将停止段错误。

关于c - 段错误 SEGV_ACCERR - 对象的无效权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46053747/

相关文章:

sockets - Netty是否支持通过UNIX域套接字的数据报包?

c - 将数据从 Host App 发送到 Chrome 扩展

c++ - 错误 : Label used but not defined when using && operator

c - 如何修复这个 cmake 文件? c 文件忽略它所依赖的 h 文件

c++ - Linux上适用于C++的任何更智能的编译系统

c - 能够改变 const 指针的值

c++ - main 在 pthread 之后不继续

c - 在 C 中为用户输入字符串指定数组大小是否重要?

linux - 如何 cat <<EOF >> 包含代码的文件?

c - 是否可以在启动时根据用户输入设置全局变量或定义?