0

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?

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
Yogita Negi
  • 63
  • 1
  • 3
  • 11

2 Answers2

4
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.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
3

This call

char** argv = calloc(4, 10);

(Note:it seems you mean

char** argv = calloc( 4, sizeof( char * ) );

end note)

with the magic number 10 allocates dynamically only one extent of memory of the size 4 * 10 that is equal to 40. So you need to call the function free only one time for the allocated extent. That is how many times malloc or calloc was called the same number of times free should be called.

I suspect that you meant something like the following

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

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

int main(void) 
{
    enum { N = 4, LEN = 10 };
    char **argv = calloc( N, sizeof( char * ) );
    
    size_t  argc = 0;
    
    argv[argc] = malloc( LEN * sizeof( char ) );
    strcpy( argv[argc++], "yogita" );
    
    argv[argc] = malloc( LEN * sizeof( char ) );
    strcpy( argv[argc++], "negi" );
    
    freeArgs( argv );
    
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335