Yogita Negi
Yogita Negi

Reputation: 63

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?

Upvotes: 0

Views: 2152

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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

Upvotes: 3

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

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.

Upvotes: 4

Related Questions