简体   繁体   English

字符串数组的分段错误

[英]Segmentation fault on array of strings

I'm trying to create a function that prints out a sequence of letters in the alphabet in order given a parameter count.我正在尝试创建一个 function,它按给定参数计数的顺序打印出字母表中的一系列字母。 For example, if the count was four the output would be strings "a" "ab" "abc" "abcd" .例如,如果计数为四,则 output 将是字符串"a" "ab" "abc" "abcd" However, if the count was more than 26 it would loop around back to 'a', so the output for count 28 would be "a"....."abcdefghijklmnopqrstuvwxyzab" .但是,如果计数超过 26,它将循环回到“a”,因此计数 28 的 output 将是"a"....."abcdefghijklmnopqrstuvwxyzab" Below is the code I have written.下面是我写的代码。 When I try to run this code however I get a segmentation fault error on the line with但是,当我尝试运行此代码时,我在以下行中收到分段错误错误

out[i][j] = let

and I am having some difficulty figuring out why.我很难弄清楚为什么。

char **sequences(int count) {

    int letter = 0;
    char **out = (char**)calloc(10, sizeof(char*));
    char **array = NULL;

    int size = 0;
    int cap = 10;
    char let;

    for (int i = 0; i < count; i++) {
                
        if (size == cap) {
            cap *= 2;
            array = (char **)realloc(out, cap*sizeof(char *));
            if (array != NULL) {
                out = array;
            } else {
                break;
            }
        }
                
        for (int j = 0; j < i; j++) {
        
            if (letter < 26) {
                let = 97 + letter;
                printf("%c\n", let);
                out[i][j] = let;
                printf("%c\n", out[i][j]);
                letter++;
                size++;
            } else {
                letter = 0;
                let = 97 + letter;
                printf("%c\n", let);
                out[i][j] = let;
                printf("%c\n", out[i][j]);
                letter++;
                size++;
            }
        }
    }
    return out;
}

int main(void) {
   
    char** first;
    char** second;    

    first = sequences(1);
    printf("sequences[0] should be \"a\", got: %s\n", sequences[0]);

    second = sequences(28);
    printf("sequences[27] should be \"ab...yzab\", got: %s\n", sequences[27]);

    return 0;
}

The main problem is that you're never allocating any memory for out[i] .主要问题是您永远不会为out[i]分配任何 memory 。 You can do this with calloc(i+1, sizeof(char)) .您可以使用calloc(i+1, sizeof(char))执行此操作。 I add 1 for the null terminator.我为 null 终结符添加 1。

There's no need to keep growing out with realloc() .无需使用realloc()继续增长out You know that the final size will be count , so just allocate that much at the beginning.你知道最终的大小是count ,所以一开始就分配那么多。

You don't need a separate letter counter.您不需要单独的letter计数器。 You can use modular arithmetic to wrap around at 26.您可以使用模块化算法在 26 处环绕。

char **sequences(int count) {
    char **out = malloc(count * sizeof(char*));
    if (out == NULL) {
        abort();
    }

    for (int i = 1; i <= count; i++) {
        out[i-1] = calloc(i+1, sizeof(char));
        if (out[i-1] == NULL) {
            abort();
        }
        for (int j = 0; j < i; j++) {
            char let = 'a' + (j % 26);
            out[i][j] = let;
            printf("%c\n", let);
        }
    }
    return out;
}

The answer is very easy.答案很简单。 You allocate an array of pointers, but you do not allocate any space for the strings.您分配了一个指针数组,但没有为字符串分配任何空间。 As you use calloc all pointers are NULL.当您使用calloc时,所有指针都是 NULL。

In this line (and in all others where you use out[i][j] )在这一行中(以及您使用out[i][j]的所有其他行)

out[i][j] = let;

you dereference NULL pointer.您取消引用 NULL 指针。 It is U ndefined B ehaviour (UB) and in your case it is expressing itself as SegFault.它是U ndefined B行为 (UB),在您的情况下,它表示为 SegFault。

Not sure what the assignment is, but you can forgo the allocations entirely, simply jump straight to the output, which is a bit simpler IMO if that's all you need:不确定分配是什么,但您可以完全放弃分配,只需直接跳转到 output,如果您只需要它,IMO 会更简单一些:

void printSequences(size_t count)
{
    for (size_t i=0; i<count; i++)
    {
        for (size_t j=0; j<=i; j++)
        {
            putchar('a' + (j % 26));
        }
        putchar('\n');
    }
    putchar('\n');
}

Working demo工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM