这是我程序的一部分,我想创建一个结构向量
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;
for (i = 1; i <= tam; i++) {
fscanf (pFile, "%[^;]", pecaJogo[i].nome);
fscanf (pFile, "%d", pecaJogo[i].qtd);
fscanf (pFile, "%d", pecaJogo[i].linha);
fscanf (pFile, "%dn", pecaJogo[i].coluna);
}
return pecaJogo;
}
如果我改变
tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca));
if (pecaJogo == NULL)
return NULL;
自
tPeca pecaJogo[tam];
它工作正常,但给出一些警告
[Warning] function returns address of local variable [-Wreturn-local-addr]
该消息清楚地表明:使用 malloc
,您正在分配空间,一旦创建它的函数 criarPecas
返回,空间就会持续存在。 您的更改分配的空间在函数返回时被回收,因此可以自由地用于其他事情,因此可以被程序的另一部分覆盖。
如果你的程序真的"运行良好",你可能只是很幸运。
正在发生的事情是
tPeca pecaJogo[tam];
是一个局部变量,因此整个数组在函数的堆栈帧中分配,这意味着它将与加载它本身的函数的堆栈帧一起被释放。
它工作的原因是因为这会导致未定义的行为,结果可能是它工作正常,但它并没有真正正常工作,只是没有任何东西覆盖分配数组的位置。
通过更改编译标志或稍微更改功能,它可能会停止工作。