C中的数组边界错误与相邻对象 [英] C Array Bounds error with adjacent object

查看:98
本文介绍了C中的数组边界错误与相邻对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://www.doc.ic.ac .UK /教学/项目/ Distinguished03 / AndrewSuffield.pdf :

 的#include<&string.h中GT;结构点¯x
{
  个char [10];
  诠释一个[4];
};无效的一声(结构X * D)
{
  strcat的(D> S,!);
}INT主要(无效)
{
  结构x深;
  的strcpy(d.s,012345678);
  D.A [0] = 3;
  D.A [1] = 2;
  D.A [2] = 1;
  D.A [3] = 0;
  爆炸(和D);
  返回[0];
}


  

在本实施例中,结构x包含一个10字节字符串紧跟一个4-整数数组。 d被初始化为9个字符的字符串(占用,因为结尾的空10个字节)和四个整数。爆炸()附加一个!到字符串,使它012345678!再加上尾随NULL。


  
  

在字符串的结尾空字节将覆盖D.A的第一个字节[0]。在
  大端主机,这将没有任何效果,因为该字节已经为零。在一个小端的主机,这将D.A [0]的值改为零


两个问题:


  1. 会不会有没有结构孔S&放大器之间present;一,因此上述说法不成立。 GCC提供返回vaue为3。

  2. 返回[0]没有我的系统(GCC)上工作。


解决方案

  1. 有很可能是该领域的空白。在任何一个现代企业制度会有的。尝试通过 strcat的更长的字符串。

  2. 返回[0] 显然是一个错字。它应该阅读返回D.A [0]

From http://www.doc.ic.ac.uk/teaching/projects/Distinguished03/AndrewSuffield.pdf:

#include <string.h>

struct x
{
  char s[10];
  int a[4];
};

void bang(struct x *d)
{
  strcat(d->s, "!");
}

int main(void)
{
  struct x d;
  strcpy(d.s, "012345678");
  d.a[0] = 3;
  d.a[1] = 2;
  d.a[2] = 1;
  d.a[3] = 0;
  bang(&d);
  return a[0];
}

In this example, struct x contains a 10-byte string immediately followed by a 4-integer array. d is initialized with a 9-character string (occupying 10 bytes because of the trailing NULL) and four integers. bang() appends a ! to the string, making it "012345678!" plus a trailing NULL.

The NULL byte at the end of the string will overwrite the first byte of d.a[0]. On a big-endian host, this will have no effect because that byte was already zero. On a little-endian host, this will change the value of d.a[0] to zero

Two questions:

  1. Will there not be structure holes present between s & a and so the above argument does not hold. gcc gives return vaue as 3.
  2. return a[0] does not work on my system (gcc).

解决方案

  1. There could very well be padding between the fields. On any modern system there will be. Try passing strcat a longer string.
  2. return a[0] is clearly a typo. It should read return d.a[0].

这篇关于C中的数组边界错误与相邻对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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