c - Undeclared array of structs being populated -
i've been doing bit of testing on code wrote when noticed had huge mistake in code regarding array sizes, yet program still ran fine. here's simplified code give idea of what's going on.
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> typedef struct { int score; }player; void printscore(player *p, int num); int main(void) { printf ("\nenter number of players (1 - 4)\n"); scanf ("%d", &numplayers); player *p = (player*)malloc(sizeof(player) * 3); (i=0;i<numplayers;i++) { printscore(p, i); } } void printscore(player *p, int num) { p[num].score = 1; printf ("%d\n", p[num].score); }
the 3 in malloc function should numplayers. if leave @ 3, , enter higher number in menu, program crash, work sometimes. how possible? if i've enough memory reserved p[0], p[1], p[2], how (for example) p[15].score exist populated?
it's called "undefined behavior". when behavior undefined - possible. accessing invalid pointer (as in example) 1 of many cases in behavior of program undefined standard, , compiler free whatever wishes.
any behavior correct behavior in such case. in case compiler doesn't anything, , program runs as if memory allocated. if os doesn't kill (= program crashes on access violation) - that's pure luck.
Comments
Post a Comment