0

This is something that's been bugging me for couple of hours now, i'm really frustrated why's this happening, so i'm asking if any good soul could possibly explain this to me.

int main()
{
    FILE* filePointer;
    int* tempPointer1;
    int* tempPointer2;

    filePointer = fopen("numbers.txt","r");

    tempPointer1 = (int*) malloc(sizeof(int)*10);
    tempPointer2 = tempPointer1;

    int j;
    for(j=0;j<10;j++)
    {
        fscanf(filePointer,"%d ",tempPointer1);
        printf("%d ", *tempPointer1);
        tempPointer1+=sizeof(int);
    }

    printf("\n");

    int i;
    for(i=0;i<10;i++)
    {
        printf("%d ", *tempPointer2);
        tempPointer2+=sizeof(int);
    }

    fclose(filePointer);
    return 0;
}

And this is the output that im getting:

1 2 3 4 5 6 7 8 9 10 

1 2 3 12337 5 6 7 8 9 10 

Can anyone explain why?

P.S If i use static int array output is the same.

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
Sir DrinksCoffeeALot
  • 593
  • 2
  • 11
  • 20

1 Answers1

4

Pointer arithmetic is designed such that the increment has the size of the type pointer to. So in this part

tempPointer1+=sizeof(int);

you are incrementing by too large a step, going beyond the bounds of the array and invoking undefined behaviour. You need to increment by 1, i.e.

tempPointer += 1;

or, more concisely,

++tempPointer1;

Note: you shouldn't cast the result of malloc in C. You can assign it to a non-void pointer directly:

tempPointer1 = malloc(sizeof(int)*10);
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Ah, thanks for the answer, but, wouldn't i be getting segmentation fault in that case if im trying to write to memory that i didnt allocate? – Sir DrinksCoffeeALot Oct 29 '15 at 16:06
  • @SirDrinksCoffeeALot You get undefined behaviour. Sometimes that might result in a segmentation fault, but it doesn't have to. – juanchopanza Oct 29 '15 at 16:07
  • @SirDrinksCoffeeALot segfaults only happen when you access a segment you don't have access to. Segments are usually chunks of memory in the the range of 1KB or even 64KB or larger (depending on how the underlying OS uses the MMU) so you can overwrite pretty far before going out of a valid segment. Almost always the chunk around 0 is marked as no access (so NULL dereferences cause faults), but beyond that, it's up to the OS to mark stuff as non-accessable or not. (IOW, don't depend on a segfault to find your bugs) – Russ Schultz Oct 29 '15 at 16:16