Home > Net >  Why am I getting an invalid pointer error when I try to free malloced pointers?
Why am I getting an invalid pointer error when I try to free malloced pointers?

Time:07-13

I'm trying to learn about how arrays of strings can be created in C using malloc (i.e. dynamically sized arrays of strings).

I can get everything working but I'm getting an "invalid pointer" error when I try to free the char* pointers stored in namesArray->data[0] and namesArray->data[1]

But if I don't use free on these two pointers, I get memory leaks.

Any idea what I'm doing wrong here? I'm stumped

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

typedef char* string;

typedef struct List_Repr {
    string *data;
} *list;

// add names to the supplied string array, myList
void addNames(list *myList, int numOfNames){
    //this is the equivalent of char** i.e. array of pointer to strings
    (*myList)->data = (string*)malloc(numOfNames*sizeof(string*)); //mallocing an array of char pointers
    
    //this is the equivalent of char* i.e. the strings themselves
    (*myList)->data[0] = (string)malloc(sizeof("Raymond") 1);
    (*myList)->data[0] = "Raymond";
    (*myList)->data[1] = (string)malloc(sizeof("George") 1);
    (*myList)->data[1] = "George";
}

//prints the names in the supplied array, myList
void printNames(list *myList){
    printf("%s\n", (*myList)->data[0]);
    printf("%s\n", (*myList)->data[1]);
}

int main()
{
    
    list namesArray = (list)malloc(sizeof(list)); // mallocing the namesArray

    
    addNames(&namesArray,2);
    printNames(&namesArray);
    
    free(namesArray->data[0]); //why does this free() command give me an error?
    free(namesArray->data[1]); //why does this free() command give me an error?
    free(namesArray->data);
    free(namesArray);
    
    return 0;
}

CodePudding user response:

(*myList)->data[0] = (string)malloc(sizeof("Raymond") 1);
(*myList)->data[0] = "Raymond";

The second assignment overwrites the malloc pointer. Which means you can't free the original pointer anymore as it is lost. Since you don't need to actually change the string you can just delete the first line completely and then there would be no need to free. Or if you want to be able to have a modifiable string then use strcpy((*myList)->data[0], "Raymond");

Another problem is that malloc(numOfNames*sizeof(string*)) should be malloc(numOfNames*sizeof(string)). Though in this case it won't cause any problem as they happen to be the same size. But it should be fixed nevertheless.

  • Related