释放的指针未在C中分配 [英] pointer being freed was not allocated in C

查看:91
本文介绍了释放的指针未在C中分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不知道下面的代码有什么问题,为什么给我错误指针未分配的错误。

Not sure what is wrong with the code below and why it is giving me the error "pointer being freed was not allocated". Using clang.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static char * messagePtr;

int main()
{

    messagePtr = (char *)malloc(sizeof(char) * 800);
    if(messagePtr == NULL) {
       printf("Bad malloc error\n");
       exit(1);
    }


    // //gameLoop();
    char outputMessage[50] = "";
    messagePtr = outputMessage;

    free(messagePtr);
    messagePtr = NULL;

    return 0;
}


推荐答案

您分配了 outputMessage 是一个数组,并转换为指向数组第一个元素的指针,该指针指向 messagePtr ,因此 messagePtr 不再指向通过 malloc()或其家人分配的内容。

You assigned outputMessage, which is an array and is converted to a pointer to the first element of the array, to messagePtr, so messagePtr no longer points at what is allcated via malloc() or its family.

传递不是 NULL 且未通过诸如 malloc()之类的内存管理功能分配的内容将调用未定义的行为。 ( N1570 7.22.3.3免费功能)

Passing what is not NULL and is not allocated via memory management functions such as malloc() invokes undefined behavior. (N1570 7.22.3.3 The free function)

请注意,他们说您不应该在C 中强制转换 malloc()的结果。

Note that they say you shouldn't cast the result of malloc() in C.

某些您可以选择:

1。停止使用 malloc()分配将被丢弃的缓冲区。

1. Stop using malloc() for allocating buffer that will be thrown away.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static char * messagePtr;

int main()
{

    // //gameLoop();
    char outputMessage[50] = "";
    messagePtr = outputMessage;

    messagePtr = NULL;

    return 0;
}

2。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static char * messagePtr;

int main()
{

    messagePtr = malloc(sizeof(char) * 800);
    if(messagePtr == NULL) {
       printf("Bad malloc error\n");
       exit(1);
    }


    // //gameLoop();
    free(messagePtr);
    char outputMessage[50] = "";
    messagePtr = outputMessage;

    messagePtr = NULL;

    return 0;
}

3。使用 strcpy()复制字符串。

3. Use strcpy() to copy strings.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static char * messagePtr;

int main()
{

    messagePtr = malloc(sizeof(char) * 800);
    if(messagePtr == NULL) {
       printf("Bad malloc error\n");
       exit(1);
    }


    // //gameLoop();
    char outputMessage[50] = "";
    strcpy(messagePtr, outputMessage);

    free(messagePtr);
    messagePtr = NULL;

    return 0;
}

这篇关于释放的指针未在C中分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆