Search code examples
carraysmallocprintfbounds

Printing a malloc() declared array - A very short code that prints out of bounds?


Why does my program print an extra element, which looks like a memory location?

CODE:

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

int main()
{
    int i;
    int *n=(int *)malloc(sizeof(int));
    n[0]=1;
    n[1]=2;
    n[2]=3;
    for(i=0;n[i];i++)
        printf("\n%d\n",n[i]);
}

OUTPUT:

1

2

3

135153

Even when I replace(in line 2 of the main block)

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

with

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

the output is the same. What have I missed here?

EDIT: Ok, so from what I've been able to understand, you can only have a condition like this when you're running through a string and not just any array, since arrays allocated using malloc() don't have a terminating character like \0.


Solution

  • You clearly need to allocate sizeof(int)*3, or you will overwrite some other memory. Here, this has no effect, because your simple application has nothing else on the heap.

    The other problem is the end condition in your for loop. n[i] means until there's by chance a 0 in the array. Your array is not 0-terminated, so it prints garbage. Use for (i=0;i<3;i++) instead.