C language, vector of struct, miss something? -


this part of program want create vector of struct

typedef struct {     char nome[501];     int qtd;     int linha;     int coluna; } tpeca;  tpeca* criarpecas(file *pfile, int tam) {     int i;           tpeca *pecajogo = (tpeca*)malloc(tam*sizeof(tpeca));     if (pecajogo == null)         return null;     (i = 1; <= tam; i++) {         fscanf (pfile, "%[^;]", pecajogo[i].nome);           fscanf (pfile, "%d", pecajogo[i].qtd);           fscanf (pfile, "%d", pecajogo[i].linha);         fscanf (pfile, "%d\n", pecajogo[i].coluna);     }     return pecajogo; } 

if change

tpeca *pecajogo = (tpeca*)malloc(tam*sizeof(tpeca));   if (pecajogo == null)       return null;    

to

tpeca pecajogo[tam]; 

it works fine give warning

[warning] function returns address of local variable [-wreturn-local-addr] 

what happening that

tpeca pecajogo[tam]; 

is local variable, , such whole array allocated in stack frame of function, means deallocated along stack frame function self loaded.

the reason it's working because causes undefined behavior, on of outcomes works correctly, it's not really working correctly, it's nothing overwriting location array allocated.

by changing compilation flags or altering funcion little bit, stop working.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -