分段故障(核心转储)问题,堆栈

时间:2014-02-25 13:06:19

标签: c stack

我不知道我在哪里出错了,任何帮助都会有所帮助。我试图用2个不同的字符串数组制作一副牌并将其打印到控制台。它编译得很好,但是当我运行它时,我得到“Segmentation fault(core dumped)”

/*
* BlackJack.c
*
*  Created on: Feb 25, 2014
*      Author: Danny Hunn
*      25 Feb 14 builds a deck for Black Jack
*/

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#define NUM_SUITS 4
#define DECK_SIZE 52
#define NUM_RANKS 13


void swap(char *first,char *second)// swapping pointers
{
char temp = *first;
*first = *second;
*second = temp;

}
void shuffle(char *deck[])
{
int seed, gen, i;
seed = (int) time(0);
srand(seed);

for(i =0; i < DECK_SIZE; i++ )
{
        gen = rand()%52;
        swap(deck[i],deck[gen]);

}

 }
 void printDeck(char *deck[])
 {
int i;
for(i=0;i<DECK_SIZE; i++)
{
    printf("%s\n", deck[i]);
}
 }

int main(int argc, char *argv[]) {
int deckIndexs = 1;
char *suit[NUM_SUITS] = {" Spades", " Hearts", " Diamonds", " Clubs"};
char *rank[NUM_RANKS] = {"Ace", "Two","Three","Four","Five","Six", "Seven", "Eight",         "Nine",
        "Ten", "Jack", "Queen", "King"};
char **deck = malloc(deckIndexs * (sizeof(*deck)));
int i,j,k;
k=0;
for(i=0; i< NUM_SUITS; i++)
{
    for(j=0; j< NUM_RANKS; j++)
    {
        char *suitTemp = suit[i];
        char *rankTemp = rank[j];
        strcat(rankTemp, suitTemp);
        deck= realloc(deck, (deckIndexs +1)*sizeof(*deck));// reallocate    memory for the size of the array
        deckIndexs++;
        deck[k] = malloc(254*sizeof(char *));// allocate memory for the new  string index
        deck[k] = rankTemp;
             k++;// increments k for the index of the array
    }

}
printDeck(deck);
shuffle(deck);

return 0;
 }

2 个答案:

答案 0 :(得分:5)

你不能使用strcat(rankTemp, suitTemp);,因为rankTemp指向一个字符串文字,通过这样做,你将修改字符串文字,非法内存指令和操作系统可以检测到对有效内存的无效访问然后os发送导致核心dunmp的SIGSEGV。

答案 1 :(得分:1)

我认为你的问题在这里

void swap(char *first,char *second)// swapping pointers
{
char temp = *first;
*first = *second;
*second = temp;

}

应该是

void swap(char *first,char *second)// swapping pointers
{
char * temp = first;
first = second;
second = temp;

}