试图了解C中的以下代码有什么问题 [英] Trying to understand what is wrong with the following code in C

查看:73
本文介绍了试图了解C中的以下代码有什么问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务来查找为什么此代码是错误的.

I have a task to find why this code is wrong.

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

#define fail(a)          ((test == 0 || test == a) ? fail##a() : 0)
#define N                (10)

int  a[N] = { 1 }; 
int* b = &a[0];


void fail1()

{
    printf("a[0] = %d\n", a[0]);
    printf("b[0] = %d\n", b[0]);
    printf("*b   = %d\n", *b);
    *b = 2;
    a[N] = 3;
    printf("*b = %d\n", *b);

}

...

int main(int argc, char **argv)
{
    int        test = 0;

    if (argc > 1) {
            sscanf(argv[1], "%d", &test);
            printf("doing test %d\n", test);
    } else
            puts("doing all tests");

    fail(1);
    fail(2);
    fail(3);
    fail(4);
    fail(5);
    fail(6);

    puts("lab6 reached the end");

    exit(0);
}

通过使用valgrind可以告诉我printf("*b = %d\n", *b);失败.我注意到通过注释a[N] = 3; valvgrind没有给出任何错误.但是我不明白为什么.我知道这与内存有关,而且我知道a[N]要求在数组外添加元素.

By using valgrind it tells me that there is a fail in printf("*b = %d\n", *b);. I have noticed that by commenting a[N] = 3; valvgrind gives no errors. But I do not understand why. I know that this has something to do with memory and I know that a[N] ask for element outside the array.

推荐答案

C数组具有从0开始的索引.对于定义为a[N]的数组,最大有效元素将为a[N-1].

C arrays have 0-based indexing. For an array defined like a[N], the maximum valid element will be a[N-1].

a[N]指向超出范围的内存.尝试访问超出范围的内存,调用未定义的行为.

a[N] points to out of bound memory. Trying to access out of bound memory, invokes undefined behavior.

现在,虽然您可能知道上述事实,但是您可能忽略了UB的作用.一旦您打到UB,便无法保证.简单的解决方案,不要编写可以调用UB的代码.

Now, while you may be knowing the above fact, what you might have ignored in the effect of UB. Once you hit UB, nothing is guaranteed. Simple solution, don't write a code which can invoke UB.

这篇关于试图了解C中的以下代码有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆