在C中使用Malloc分配数组大小

发布于 2024-10-21 04:41:45 字数 377 浏览 1 评论 0原文

在我正在编写的程序中,我有一个帐户数组(帐户是我创建的结构)。我需要它对我的程序中的所有函数和线程可见。但是,在 main 函数弄清楚之前,我不知道它的大小。所以我用以下方法创建了它: 账户*账户;

并尝试在 main 中为其分配空间:

number of accounts = 100 //for example
accounts = (account*)malloc(numberOfAccounts * sizeof (account));

但是,它似乎将数组调整为大于所需的大小。例如,accounts[150] 存在,等等。

我做错了什么吗?如何使帐户大小恰好为 100? 谢谢

In a program I'm writing, I have an array of accounts(account is a struct I made). I need this visible to all functions and threads in my program. However, I won't know the size it has to be until the main function figures that out. so I created it with:
account *accounts;

and try to allocate space to it in main with this:

number of accounts = 100 //for example
accounts = (account*)malloc(numberOfAccounts * sizeof (account));

However, it appears to be sizing the array larger than it needs to be. For example, accounts[150] exists, and so on.

Is there anything I am doing wrong? How can I get the size of accounts to be exactly 100?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

十级心震 2024-10-28 04:41:46

仅仅因为它有效并不意味着它作为您分配的内存的一部分存在,很可能它属于其他人。

C 不关心也不知道你的 account* 来自 malloc,它只知道那是一个指向 sizeof(account) 的内存指针。

account[150] 从指针中的值访问第 150 个帐户大小的对象,该对象可能是随机数据,也可能是其他数据,具体取决于您的系统,甚至可能是您的程序。

事情看起来“有效”的原因是,无论发生什么,它都是不重要的,但情况可能并不总是如此。

Just because it works doesn't mean it exists as part of the memory you allocated, most likely it belongs to someone else.

C doesn't care or know that your account* came from malloc, all it knows is that is a memory pointer to something that is sizeof(account).

accounts[150] accesses the 150th account-sized object from the value in the pointer, which may be random data, may be something else, depending on your system it may even be your program.

The reason things seem to "work" is that whatever is there happens to be unimportant, but that might not always be the case.

倾城月光淡如水﹏ 2024-10-28 04:41:45

你不能这样做 - malloc() 不提供任何关于它实际分配多少内存的保证(除非它成功,它将返回一个指向至少同样多的内存< /em> 按照您的要求)。如果您访问超出您要求的范围的任何内容,则会导致未定义的行为。这意味着它可能看起来有效,但您对此无能为力。

顺便说一句,在 C 中,您不需要对 malloc() 返回的值进行类型转换。

You can't do that - malloc() doesn't provide any guarantees about how much memory it actually allocates (except that if it succeeds it will return a pointer to at least as much as you requested). If you access anything outside the range you asked for, it causes undefined behaviour. That means it might appear to work, but there's nothing you can do about that.

BTW, in C you don't need to typecast the returned value from malloc().

囍孤女 2024-10-28 04:41:45

尽管看起来像这样,但 accounts[150] 并不真正存在。

那么为什么你的程序还能继续运行呢?嗯,这是因为即使 accounts[150] 不是一个真正的元素,它也位于您的程序允许访问的内存空间内。

C 不包含索引的运行时检查 - 它只是计算适当的地址并访问它。如果您的程序无权访问该内存地址,它将因分段错误(或者用 Windows 术语来说,访问冲突)而崩溃。另一方面,如果程序允许访问该内存地址,那么它将简单地将该地址处的任何内容视为帐户

如果您尝试修改它,几乎任何事情都可能发生 - 根据多种因素,它可能会修改程序中的其他一些变量,或者在一些非常不幸的情况下,它甚至可能会修改程序代码本身,这可能会导致各种奇怪的行为(包括崩溃)。如果 malloc(无论出于何种原因)分配的内存多于您明确请求的内存(这是可能的),甚至可能不会观察到任何副作用。

如果您想确保在运行时捕获此类错误,则必须实现自己的检查和错误处理。

Even though it may look like it, accounts[150] does not truly exist.

So why does your program continue to run? Well, that's because even though accounts[150] isn't a real element, it lies within the memory space your program is allowed to access.

C contains no runtime checking of indexes - it just calculates the appropriate address and accesses that. If your program doesn't have access to that memory address, it'll crash with a segmentation fault (or, in Windows terms, an access violation). If, on the other hand, the program is allowed to access that memory address, then it'll simply treat whatever is at that address as an account.

If you try to modify that, almost anything can happen - depending on a wide variety of factors, it could modify some other variables in your program, or given some very unlucky circumstances, it could even modify the program code itself, which could lead to all kinds of funky behavior (including a crash). It is even possible that no side effects can ever be observed if malloc (for whatever reason) allocated more memory than you explicitly requested (which is possible).

If you want to make sure that such errors are caught at runtime, you'll have to implement your own checking and error handling.

江湖彼岸 2024-10-28 04:41:45

我似乎没有发现你提供的东西有什么问题。如果您有一个结构,例如:

struct account{
  int a,b,c,d;
  float e,f,g,h;
}

那么您确实可以使用以下命令创建帐户数组:
struct account *accounts = (struct account *) malloc(numAccounts * sizeof(account));
请注意,对于 C 来说,void*(malloc 的返回类型)的转换不需要。它将自动升级。

[编辑]
啊啊!我现在看到你的问题了!正确的。是的,您仍然可以访问帐户[150],但基本上发生的情况是帐户将指向某个内存位置。 accounts[150] 只是进一步指向结构体大小的 150 倍。您可以通过执行以下操作获得相同的结果:
*(accounts + 150),其基本意思是:给我位置accounts+150 处的值。

该内存根本没有被保留,因此会导致未定义的行为。基本上可以归结为:不要这样做!

I can't seem to find anything wrong with what you provide. If you have a struct, e.g.:

struct account{
  int a,b,c,d;
  float e,f,g,h;
}

Then you can indeed create an array of accounts using:
struct account *accounts = (struct account *) malloc(numAccounts * sizeof(account));
Note that for C the casting of void* (retun type of malloc) is not necessary. It will get upcasted automatically.

[edit]
Ahhh! I see your problem now! Right. Yes you can still access accounts[150], but basically what happens is that accounts will point to some memory location. accounts[150] simply points 150 times the size of the struct further. You can get the same result by doing this:
*(accounts + 150), which basically says: Give me the value at location accounts+150.

This memory is simply not reserved, and therefore causes undefined behavior. It basically comes down to: Don't do this!

心安伴我暖 2024-10-28 04:41:45

你的代码没问题。当您说帐户[150]退出时,您的意思是退出还是存在?

如果您的代码在访问accounts[150](假设numberOfAccounts = 100)时崩溃,那么您正在访问分配的内存之外是可以预料的。

如果您的意思是存在,但实际上并非如此,您只是走出数组的末尾,而您返回的指针指向与您分配的内存区域不同的区域。

Your code is fine. When you say accounts[150] exits do you mean exits or exists?

If your code is crashing when accessing accounts[150] (assuming numberOfAccounts = 100) then this is to be expected you are accessing memory outside that you allocated.

If you meant exists it doesn't really, you are just walking off the end of the array and the pointer you get back is to a different area of memory than you allocated.

給妳壹絲溫柔 2024-10-28 04:41:45

如果该地址非零,则帐户大小恰好是从 malloc 结果指针开始的 100 结构。

Size of accounts is exacly for 100 structures from malloc result pointer starts if this address is non-zero.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文