Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the size of reserved memory for a character array in C

Tags:

c

string

pointers

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.

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?

I tried:

sizeof(dest)

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.

I also tried:

strlen(dest)

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"???

Example:

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

What is "someFunction"?

Thanks in advance!

like image 810
Daan Avatar asked Dec 27 '22 10:12

Daan


2 Answers

Once you pass a char pointer to the function you are writing, you will loose knowledge for how much memory is allocated to s. You will need to pass this size as argument to the function.

like image 136
Ivaylo Strandjev Avatar answered Dec 29 '22 01:12

Ivaylo Strandjev


You can use sizeof to check at compile time:

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

Note that this fails if s is a pointer:

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

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 );
like image 21
William Pursell Avatar answered Dec 29 '22 00:12

William Pursell