free(ptr)有时会崩溃,指针总是有效的

时间:2014-11-26 11:31:22

标签: c segmentation-fault free

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

    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 感谢

3 个答案:

答案 0 :(得分:3)

当您尝试覆盖某些动态分配的内存时,这是堆损坏的情况。

答案 1 :(得分:3)

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

看起来不错。我认为应该是

encr_streams = malloc(key_length * sizeof *encr_streams);

因为您似乎打算分配一个指向uint8_t的指针数组。然后你可能还需要通过某种方式初始化该数组的元素。

答案 2 :(得分:1)

如果您在Linux上编程,请在valgrind内存调试器下运行代码:

对于Windows ...你可能想尝试使用MS AppVerifier,虽然我已经多年没有使用它并且几乎忘记了它的一切: - (