seg fault / pointer help

时间:2014-10-09 18:56:59

标签: pointers segmentation-fault

所以我知道编程的基础,我有相当多的java经验,但我现在正在学习C学校。我仍然不完全理解整个指针方面,这是我确定造成的错误。这个程序在我的计算机上运行时工作正常,但是当我尝试在我的学校unix shell上运行它时,它给了我一个seg错误。如果有人可以向我解释为什么或如何滥用指针,这对我有很大帮助。

//Matthew Gerton
//CS 222 - 002
//10/10/14
//HW Six

//libraries
#include<stdio.h>
#include<string.h>
#define max_Length 256

//prototypes
void decode(char *a, char *b);
void trimWhite(char *a);
void encode(char *a, char *b);

int main(void)
{
    //character arrays
    char coded[max_Length], decoded[max_Length];

    //decode the sample phrase
    char sample[] = {'P','H','H','W','D','W','C','R','R','F','D','Q','F','H','O','H','G','J',
                'R','W','R','P','H','W','U','R','K','R','W','H','O','U','R','R','P','I','R','X','U'};

    decode(sample, decoded);

    //scans a user input string to decode, and decodes it
    printf("\nPlease enter a phrase to decode: ");
    gets(coded);
    trimWhite(coded);
    decode(coded, decoded);

    //scans a user input phrase to encode
    printf("\nPlease enter a phrase to encode: ");
    gets(coded);
    trimWhite(coded);
    encode(coded, decoded);
}

//removes any spaces from the input
void trimWhite(char *a)
{
    char temp[max_Length];
    int  z=0, y=0;
    while(a[z]!='\0')
    {
        if(a[z]!=' ')
        {
           temp[y]=a[z];
           y++;
        }
        z++;
    }
    temp[y] = '\0';
    strcpy(a,temp);
  }

//decodes any phrase
void decode(char *a, char *b)
{
    int i=0,n;
    memset(b, '\0', sizeof(b));
    while(a[i]!='\0')
    {
        n=(int)a[i];
        if(n<97)
            n=n+32;
        if(n<=99)
            n=n+23;
        else
            n = n-3;
        b[i]= (char) n;
        i++;
    }
    b[i]='\0';
    printf("Coded message: %s\n", a);
    printf("Decoded message: %s\n", b);
}
//codes an input phrase
void encode(char *a, char *b)
{
    int i=0,n;
    memset(b, '\0', sizeof(b));
    strcpy(b,a);
    while(a[i]!='\0')
    {
        n=(int)a[i];
        if(n<97)
            a[i] = (char)(n+32);
        if((n>120)
            a[i] = (char)(n-23);
        else
            a[i] = (char)((n+3);

        i++;
    }
    printf("Coded message: %s\n", a);
}

1 个答案:

答案 0 :(得分:0)

  • 您的主要问题在于:

    char sample[] = {'P','H','H', /* snip */ ,'R','X','U'};
    

    sample[]数组不会以零结尾,这可能导致decode()函数复制多于预期的字符,从而覆盖其他变量。使用初始化列表时,您需要显式添加终止零:

    char sample[] = {'P','H','H', /* ... */ ,'R','X','U',0};

    或者您可以使用字符串文字初始化数组, 包含终止零:

    char sample[] = "PHHWDWCRRFDQFHOHGJRWRPHWURKRWHOURRPIRXU";
    
  • 您应该阅读"Why is the gets function dangerous"

  • ...

    void decode(char *a, char *b)
    {
        int i=0,n;
        memset(b, '\0', sizeof(b));
    

    另请注意,传递给函数时,数组的大小会丢失。该函数仅接收指向其第一个元素的指针。上面的memset()调用只会为sizeof(char*)个字节(通常为4或8)。这无关紧要,因为据我所知,你只需要将第一个字节归零。你可以简单地写:

        b[0] = 0;