Sushanth Ambati
Sushanth Ambati

Reputation: 3

malloc: *** error for object 0x120e06884: pointer being freed was not allocated

I have written some code on to find the number of times the characters repeated in the string.Considered 2 pointers and allocated memory dynamically, then input the string into one of the pointers.Then copying the characters without redundancies into the another pointer and finally comparing it, incrementing the count and printing to the screen.

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

void string_cpy(char *from, char *to);
int len(char *p);

int main()
{
    char *name, *copy, *hold;
    int i, j, lent, count = 0, length;

    name = (char *)calloc(25, sizeof(char));
    copy = (char *)calloc(25, sizeof(char));

    printf("Give a string:");
    scanf("%s", name);
    puts("");

    string_cpy(name, copy);
    hold = name;
    lent = len(copy);   //l=4
    length = len(name); //lenght = 5
    printf("Characters and their corresponding frequencies\n");

    for (i = 0; i < lent; ++i)
    {
        for (j = 0; j < length;)
        {
            if (*(copy) == *(name))
            {
                ++count;
                ++name;
                ++j;
            }
            else
            {
                ++j;
                ++name;
            }
        }
        name = hold;
        printf("%c-%d\n", *(copy), count);
        count = 0;
        ++copy;
    }

    free(name);
    free(copy);

    return 0;
}

void string_cpy(char *from, char *to)
{
    int i, j, k, l, ex;
    char key;
    l = len(from); //l=5
    char *t = to;

    for (i = 0, j = 0; i < l; ++i)
    {
        key = *(from + i);
        ex = 0;
        for (k = 0; k < i; ++k)
        {
            if (*(to + k) == key)
            {
                ex = 1;
            }
        }
        if (!ex)
        { //if(ex==0)
            strcpy((to + j), (from + i));
            ++j;
        }
    }
}

int len(char *p)
{
    int leng = 0;
    while (*p != '\0')
    {
        ++leng;
        ++p;
    }
    return leng;
}

when I try to free() up both the pointers or the '''char *copy''' it throws me an error ->malloc: *** error for object 0x120e06884: pointer being freed was not allocated ->malloc: *** set a breakpoint in malloc_error_break to debug

This was done on my Mac OS

Upvotes: 0

Views: 2885

Answers (1)

0___________
0___________

Reputation: 67721

You change the value of the calloced pointer. It does not reference anymore the allocated memory block.

++copy;

Upvotes: 1

Related Questions