Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

315
Views
C: malloc error-pointer being freed was not allocated

I am trying to return an array of string from a function and then free the memory it used. The code is below:

int main(int argc, const char * argv[])
{
    for (int m = 0; m < 10000; m++) {
        char **data = dataTest();

        int i = 0;
        while(data[i]) {
            printf("%p ",data[i]);
            free(data[i]);
            i++;
        }
        printf(" address= %p.\n",data);
        free(data);
    }

    return 0;
}

Here is the function:

char **dataTest()
{
    char *row[] = {"this", "is", "a", "data", "string", NULL};
    char **str = row;
    char **dataReturn = (char **) malloc(sizeof(char *) * 6);

    int i = 0;
    while (*str) {
        dataReturn[i] = malloc(sizeof(char) * strlen(*str));
        strcpy(dataReturn[i++], *str);
        str++;
    }

    return dataReturn;
}

It runs well in the beginning, but soon the error occurs. Below is the result. The address goes wrong somehow and the malloc error happens. Anyone has met the same problem before?

0x100300030 0x100300040 0x100300050 0x100300060 0x100300070  address= 0x100300000.
0x100300030 0x100300040 0x100300050 0x100300060 0x100300070  address= 0x100300000.
0x100400030 0x100300030 0x100300040 0x100300050 0x100300060  address= 0x100400000.
testC(562,0x7fff73e71310) malloc: *** error for object 0x3000000000000:     
pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
0x100300060 0x100300070 0x100300030 0x100300040 0x100300050 0x3000000000000                 
Program ended with exit code: 9
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to add this to just before return dataReturn; in your dataTest function:

dataReturn[i] = NULL ;

otherwise your while (data[i]) {} will continue further than wanted.

And instead of:

dataReturn[i] = malloc( sizeof(char) * (strlen(*str)) );

write:

dataReturn[i] = malloc(strlen(*str) + 1);

in order to allocate space for the terminating zero.

BTW sizeof (char) is always 1.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!