Error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <alloc.h>
main()
{
    int *v, t;
    v = (int *)malloc(80);
    if (v == NULL)
    {
        printf("Memoria nao disponivel");
    }
    else
    {
        for (t=0; t<= 40; t=t+ 1)
        {
            v[t] = t*t;
        }
        for (t = 0; t <= 40; t = t + 1)
        {
            printf("%d ", v[t]);
        }
        free(v);
    }
}


What's the error ?
Put it in a compiler and see?
there is no header file called alloc.h
u cannot use the malloc function available in only in stdlib function so u have to include the header file stdlib.h and u cannot remove the header file alloc.h
closed account (1vRz3TCk)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>  /* 1: here*/

/*2: here*/int main(void)
{
    int *v, t;
    v = (int *)malloc(80);  /*see 3: and 4: */
    if (v == NULL)
    {
        printf("Memoria nao disponivel");
    }
    else
    {
        for (t=0; t<= 40; t=t+ 1)  /* 3: here*/
        {
            v[t] = t*t;
        }
        for (t = 0; t <= 40; t = t + 1) /*4: here*/
        {
            printf("%d ", v[t]);
        }
        free(v);
    }
}


1: as has been said [stdlib.h ]
2: should return int (and in this case specify no parameters)
3: & 4: You allocate 80 bytes to v (assuming 32 -bit ints) that is only enough room for 20 ints (v[0]...v[19]) you are indexing past this in your for loops. If you want to index forty elements in your array you should also not do
for (t=0; t<= 40; t=t+ 1) as that is 41 (0 ...40), should be more like
for (t=0; t< 40; ++t) and your maloc would be
v = (int *)malloc(40 * sizeof(int));
Last edited on
Topic archived. No new replies allowed.