Search code examples
cdynamic-memory-allocationfreec-stringscalloc

Free(): invalid pointer in C program


I am executing following C program and getting runtime error as "free(): Invalid Pointer"

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

static void freeArgs(char** args);

int main()
{
    char** argv = calloc(4, 10);
    int  argc = 0;

    argv[argc++]="yogita";
    argv[argc++] ="negi";
    argv[argc] = NULL;
    freeArgs(argv);
    return 0;
}

static void freeArgs(char** args)
{
    char** af = args;
    for (; *af; af++)
        free(*af);
    free(args);
}

Can anyone suggest me the solution?


Solution

  • free(*af);
    

    tries to free memory that was not allocated through malloc/calloc:

    argv[argc++]="yogita";
    

    "yogita" is a string literal, thus not dynamically allocated. You can't free its memory.