简体   繁体   English

释放的指针未分配/ Segfault

[英]Pointer being freed was not allocated / Segfault

I thought I understood how dynamic memory worked basically, but I did the following. 我以为我了解动态内存的基本工作原理,但是我做了以下工作。 I use this function to allocate dynamic memory: 我使用此函数分配动态内存:

int get_alota_mem(char*** const ptr)
{
    int result = EXIT_SUCCESS;
    bool success = true;

    if (success && (*ptr = calloc(10, sizeof **ptr)) == NULL)
    {
        result = EXIT_FAILURE;
        success = false;
    }

    for (int i = 0; i < 10; i++)
    {
        if (success && ((*ptr)[i] = calloc(20, sizeof ***ptr)) == NULL)
        {
            result = EXIT_FAILURE;
            success = false;
        }
    }

    return result;
}

I use this function to free the allocated dynamic memory: 我使用此函数释放分配的动态内存:

void free_alota_mem(char** const ptr)
{
    for (int i = 0; i < 10; i++)
    {
        free(ptr[i]);  // segfault!
        ptr[i] = NULL;
    }

    free(ptr);
}

In between those two calls I can use the memory and don't encounter any segfaults. 在这两个调用之间,我可以使用内存,并且不会遇到任何段错误。 But when I try to free the memory, I get a segfault with the first value I try to free. 但是,当我尝试释放内存时,我会遇到尝试释放的第一个值出现段错误。

I know I could just do char* ptr[10] and just use an auto allocated array instead of a dynamically allocated pointer, which would save me some hassle, but I wanted to try and make this work. 我知道我可以只做char* ptr[10]并只使用自动分配的数组而不是动态分配的指针,这可以为我省去一些麻烦,但是我想尝试使这项工作变得可行。

EDIT: My main: 编辑:我的主要:

int main(void)
{
    char** mem = NULL;
    get_alota_mem(&mem);
    mem[0] = "Hello";
    mem[1] = "world";
    free_alota_mem(mem);
}

You tried to free string literals. 您试图释放字符串文字。 Passing pointer that is not NULL and not what is allocated via memory management functions such as malloc() to free() will invoke undefined behavior . 将不是NULL且不是通过诸如malloc()内存管理功能分配的指针的指针传递给free()将调用未定义的行为

To copy strings, use strcpy() function. 要复制字符串,请使用strcpy()函数。

#include <string.h>

int main(void)
{
    char** mem = NULL;
    get_alota_mem(&mem);
    strcpy(mem[0], "Hello");
    strcpy(mem[1], "world");
    free_alota_mem(mem);
}

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

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