[Solved] pointer being freed was not allocated in C


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.

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)

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

Some of your options are:

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. Free the buffer before throwing it away.

#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. 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;
}

1

solved pointer being freed was not allocated in C