坏代码或坏编译器

坏代码或坏编译器

本文介绍了坏代码或坏编译器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



AC程序,其代码以下面的简化示例为代表

已在多个编译器上编译后运行了几年

年。然而,对于一个相当新的GCC编译器,它会在指示的指令处导致

分段错误。


简而言之,当写入数组元素时会出现问题

数组指针是由数组索引中的函数分配的。


我的问题:这是不好的C代码,不明智 $ C $ b(注意:这个简单的例子显然不是生产代码。)


感谢您的帮助。


问候,

Charles Sullivan


-------------- ---------------------------

#include< stdio.h>

#include< stdlib.h>


int nextindex(int ** arrayp)

{

static int lastindex = -1;


if(* arrayp == NULL)

* arrayp = calloc(100,sizeof(int));


返回++ lastindex;

}


int main(无效)

{

int j;

int * array = NULL;


for(j = 0; j< 10; j ++)

array [nextindex(& array)] = 10 * j; / *段错误* /


for(j = 0; j
printf(" array [%d] =%d \ n",j,array [j]);


返回0;

}

----- ---------------------------------


A C program with code typified by the following pared-down example
has been running after compilation on numerous compilers for several
years. However with a fairly recent GCC compiler it results in a
segmentation fault at the indicated instruction.

Briefly, the problem occurs when writing to an array element when
the array pointer is allocated by a function in the array index.

My question: Is this bad C code, "unwise" C code, or a compiler bug?

(Note: This simple example is obviously not production code.)

Thanks for your help.

Regards,
Charles Sullivan

-----------------------------------------
#include <stdio.h>
#include <stdlib.h>

int nextindex ( int **arrayp )
{
static int lastindex = -1;

if ( *arrayp == NULL )
*arrayp = calloc(100, sizeof(int));

return ++lastindex;
}

int main ( void )
{
int j;
int *array = NULL;

for ( j = 0; j < 10; j++ )
array[nextindex(&array)] = 10 * j; /* segfaults */

for ( j = 0; j < 5; j++ )
printf("array[%d] = %d\n", j, array[j]);

return 0;
}
--------------------------------------

推荐答案



您不应该检查calloc是否返回有效指针? (我知道

它与malloc有点不同)


无论如何,* arrayp(或main()中的数组)的值是多少? ,就在它出现之前

错了?


-

Bartc


Aren''t you supposed to check whether calloc returns a valid pointer? (I know
it''s a little different to malloc)

What''s the value of *arrayp (or array in main()) anyway, just before it goes
wrong?

--
Bartc




错误的代码。 seg故障线与


*相同(数组+ nextindex(&数组))= 10 * j;


操作数可以按任何顺序进行评估。所以编译器是允许的,例如允许生成将数组值加载到

寄存器中的代码,然后是(可能内联的)nextindex

计算。我的猜测是这就是发生了什么。

Bad code. The seg fault line is the same as

*(array + nextindex(&array)) = 10 * j;

The operands can be evaluated in either order. So the compiler is
allowed to e.g generate code that loads the value of array into a
register, followed by the (potentially inlined) nextindex
computation. My guess is that this is what''s happening.



这篇关于坏代码或坏编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 19:30