0

I've got a problem with dynamic array. I have to write a program which adds a character to dynamic array starting with 0 elements going to 10. I mustn't use realloc and I have to free the array each time.

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

void add(int **ptab, int n, int new_elem)
{

    int *tab2, y;

    tab2 = malloc(n * sizeof(int));

    for(y = 0; y < n; y++)
    {
        tab2[y] = (*ptab)[y];
    }
    *ptab = tab2;   
    (*ptab)[n] = new_elem;
    free(ptab);
}

main()
{
    int *ptab, i, x;

    *ptab = NULL;
    for(i = 0; i < 10; i++)
    {
        scanf("%d", &x);
        add(&ptab, i, x);
    }
    for(i = 0; i < 10; i++)
    {
        printf("%d", ptab[i]);
    }
}
3
  • 5
    What is your question? Commented Dec 4, 2014 at 18:25
  • *ptab = NULL; --> ptab = NULL;, tab2=malloc (n * sizeof(int)); --> tab2=malloc ((n+1) * sizeof(int)); Commented Dec 4, 2014 at 18:31
  • function add() malloc, need to insert '+1' so will be room for an element to be added. Otherwise this line: (*ptab)[n] = new_elem; is writing past the end of the allocated memory. also when function add() parameter 'n' is 0, malloc returns NULL, so be sure to add the '+1' to the malloc. Note: checking the returned value from malloc for successful operation would have caught that problem. Commented Dec 4, 2014 at 22:42

1 Answer 1

3
*ptab=tab2;   
(*ptab)[n]=new_elem;
free(ptab);

should be

free(*ptab);
*ptab=tab2;   
(*ptab)[n]=new_elem;

Currently, you're overwriting the old array pointer before freeing it, so you no longer know what you're supposed to free.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, there is a tremendous difference between the original free(ptab) and this corrected version's free(*ptab).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.