本文介绍了是否释放其被分配到一个char *(由`malloc`分配)一个int *未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题可能混淆。假设 STR 是按分配的指针的malloc。 PTR ,类型为int * ,分配给它,如由下面的code片段被释放

 的char *海峡=的malloc(64);
为int * PTR = str中;免费(PTR);

我试图编译上面的code。它只是给出了一个警告:

  source_file.c:在函数'主':
source_file.c:10:16:警告:初始化从兼容的指针类型
     为int * PTR = str中;
                ^

请问上述code未定义行为?结果
难道上述code段释放由分配的内存的malloc STR


解决方案

It depends.

From C11 draft 6.3.2.3/7:

As the alignment for a char might be different from an int, that is probably less restrictive, assigning a char * pc to an int * pi might lead to pi being misaligned.

However for the specific example given by the OP:

char * pc = malloc(64);
int * pi = pc;

the behaviour would be defined, as (See Alter Mann's comment) malloc() is guaranteed to return a block of memory properly aligned.

From C11 draft 7.22.3:

An example which would lead to undefined behaviour, due to misalignment, is:

char * pc = malloc(64);
int * pi = pc + 1;


In case the former assignment would have introduced undefined behaviour this question is irrelevant, as anything could happen with UB having been invoked already.

If else the prior assignment wouldn't have invoked UB, the call to free() would perfectly de-allocate the block of memory referenced, as converting back the pointer value from int * to void *, as originally provided by malloc(), is well defined.

From C11 draft 6.3.2.3/7 (cont/):

and

From C11 draft 6.3.2.3/1:

这篇关于是否释放其被分配到一个char *(由`malloc`分配)一个int *未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 02:59