c - free(ptr) 有时会崩溃,指针始终有效

标签 c segmentation-fault free

我正在尝试创建一些动态分配的字节流,并在其他地方执行它们的副本。我的代码是这样的(之前我没有从电脑上输入:)):

    void construct_cypherstreams(uint8_t * stream, int key_length, int stream_length, uint8_t ** encr_streams, int * bytes_in_stream) {
        // chyperstream = the stream formed of every ith byte
        uint8_t * cypherstream;
        int length;
        length = stream_length / key_length + 1;
        // each byte of the key can have values
        // between 0 and 256
        int i = 0;
        int num_added = 0;
        for (int k = 0; k < key_length; k++) {
            printf("\n%s %d\n", "iteration", k);
            i = k; num_added = 0;
            cypherstream = (uint8_t *)malloc(length * sizeof (char));
            if (cypherstream == NULL) {
                printf("%s\n", "could not allocate");
                exit(1);
            }
            else {
                printf("%s\n", "succesfully allocated");
            }
            while (i < stream_length) {
                // construct cypherstream
                cypherstream[num_added] = stream[i];
                num_added++;
                i += key_length;
            }
            printf("\n%s\n", "created cypherstream:");
            for (int m = 0; m < num_added; m++) {
                printf("%X", cypherstream[m]);
            }
            printf("\n");
            printf("%s\n", "making deep copy...");
            encr_streams[k] = (uint8_t *)malloc(num_added * sizeof(char));
            // perform deep copy of characters
            for (int n = 0; n < num_added; n++) {
                encr_streams[k][n] = cypherstream[n];
            }
            printf("%s\n", "done making deep copy");
            free(cypherstream);
            printf("%s\n", "succesfully freed");
            printf("%s %d\n", "position:", k);
            printf("%s %d\n", "num_added:", num_added);
            bytes_in_stream[k] = num_added;
            printf("%s\n", "iteration ended");
        }
    }

我这样调用它:

    uint8_t ** encr_streams;
    int  * bytes_in_stream;
    encr_streams = (uint8_t **)malloc(key_length * sizeof **encr_streams);
    bytes_in_stream = (int *)malloc(key_length * sizeof *bytes_in_stream);
    construct_cypherstreams(stream, key_length, stream_length, encr_streams, bytes_in_stream);

现在我的程序有时会运行,有时会崩溃。 我现在被困在这里,我真的需要一些帮助。 编译器:msvc 谢谢

最佳答案

encr_streams = (uint8_t **)malloc(key_length * sizeof **encr_streams);

只是看起来不对。我觉得应该是

encr_streams = malloc(key_length * sizeof *encr_streams);

因为您似乎打算分配一个指向uint8_t的指针数组。然后您可能还必须通过某些东西初始化该数组的元素。

关于c - free(ptr) 有时会崩溃,指针始终有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27148052/

相关文章:

c++ - 二维 vector 的 push_back 中的段错误

c - 函数结束后如何 "free"变量?

c - 如何在 C 语言中为特定的结构类型正确使用 free

c - 具有逻辑运算符的混合增量运算符

c - scanf 之后 fgets 不起作用

c - 使用指向结构的指针数组将结构的元素设置为随机 double 值

c - 链表添加函数导致段错误

c - 终端中的链表段错误,但调试器中没有

c - 使用 malloc 和 free 理解指针

c - 微 Controller 编程