查找保留内存的大小在C语言的字符数组 [英] Find the size of reserved memory for a character array in C

查看:121
本文介绍了查找保留内存的大小在C语言的字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学C,并作为一个开始,我掀起写我自己的实践中的strcpy。我们知道,原来的strcpy容易使得安全问题,所以我给自己写了一个安全的strcpy任务。

I'm trying to learn C and as a start, i set off writing a strcpy for my own practice. As we know, the original strcpy easily allows for security problems so I gave myself the task to write a "safe" strcpy.

我选择的路径是请检查是否源字符串(字符数组)的目标内存实际相符。正如我的理解是,在C字符串无非就是一个指针更上一个字符数组,为0x00终止。

The path I've chosen is to check wether the source string (character array) actually fits in the destination memory. As I've understood it, a string in C is nothing more than a pointer to a character array, 0x00 terminated.

所以我的挑战是如何找到编译器实际上多少内存预留给目标字符串?

So my challenge is how to find how much memory the compiler actually reserved for the destination string?

我试过:

sizeof(dest)

但是,这并不工作,因为它会返回(因为我后来发现)dest的大小,这实际上是一个指针,我的64位计算机上,总是会返回8。

but that doesn't work, since it will return (as I later found out) the size of dest which is actually a pointer and on my 64 bit machine, will always return 8.

我也试过:

strlen(dest)

但是,这并不工作,可能是因为它会直接返回长度遇到的第一个为0x0到,这并不一定反映实际的内存保留。

but that doesn't work either because it will just return the length until the first 0x0 is encountered, which doesn't necessarily reflect the actual memory reserved.

因此​​,这所有款项到以下问题:如何找到我们的编译器多少内存留给我的目的地串???

So this all sums up to the following question: How to find our how much memory the compiler reserved for my destination "string"???

例如:

char s[80] = "";
int i = someFunction(s); // should return 80

什么是someFunction?

What is "someFunction"?

在此先感谢!

推荐答案

您可以用sizeof的检查在编译时:

You can use sizeof to check at compile time:

char s[80] = "";
int i = sizeof s ; // should return 80

请注意,如果s是一个指针失败:

Note that this fails if s is a pointer:

char *s = "";
int j = sizeof s;  /* probably 4 or 8. */

数组不是指针。若要跟踪分配的指针大小,程序则只是必须保持它的轨道。此外,您不能传递一个数组给一个函数。当您使用数组作为参数传递给一个函数,编译器转换,为一个指向第一个元素,所以如果你想要的大小是avaliable所调用的函数,它必须作为参数传递。例如:

Arrays are not pointers. To keep track of the size allocated for a pointer, the program simply must keep track of it. Also, you cannot pass an array to a function. When you use an array as an argument to a function, the compiler converts that to a pointer to the first element, so if you want the size to be avaliable to the called function, it must be passed as a parameter. For example:

char s[ SIZ ] = "";
foo( s, sizeof s );

这篇关于查找保留内存的大小在C语言的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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