This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 10 years ago.
I am wondered about the memory usage of variables and I tried this :
#include <iostream>
int main()
{
char* testChar1 = "Hi";
char* testChar2 = "This is a test variable";
char* testChar3 = "";
std::cout <<sizeof(testChar1)<<std::endl;
std::cout <<sizeof (testChar2) <<std::endl;
std::cout <<sizeof(testChar3)<<std::endl;
}
output is :
4
4
4
I think I am not doing the right thing. I want to know how much memory every variable uses in stack .
EDIT 1
At the same time if I does char* testChar3 = NULL; the program crashes. So does it mean there is no memory usage for the same?
In addition to using strlen, you could also use sizeof on a
char testChar1[] = "Hi";
EDIT: yes, this includes the null terminator, which IMO is an advantage over strlen. The actual size does include the null terminator.
You simply print the size of the pointers, they always will be the same. What you need is to multiply strlen for the strings by the size of a single char.
EDIT: as per my comment and the correction from #Suma:
cout << (strlen(testChar) + 1) * sizeof(char) + sizeof(testChar);
The 1 is needed for the terminating zero character.
sizeof(testChar1) return size of pointer, if you want to test string length try replace sizeof with strlen
In this instance you're only printing the size of the pointers and not the chars. So really, you would want to print the pointer, then dereference it and print the size of the memory it points to as well.
You are actually printing the amonut of bytes a pointer takes on your system . I think what you need to do is to use strlen function . Check it out here . strlen
std::cout<<strlen(testChar1)<<std::endl;
std::cout <<strlen(testChar2) <<std::endl;
std::cout <<strlen(testChar3)<<std::endl;
I want to know how much memory every variable uses in stack .
What your programm print is exactly what you want.
Read the other answer if what you really want is to know how much memory (where??!!) occupy the char-strings pointed by yours variables - pointers.
Related
This question already has answers here:
Char and strcpy in C
(5 answers)
Closed 2 years ago.
I want to allocate space for char array (string) in C++. When I allocate memory for 10 chars, I can also assign more characters to the char array. When I print it, it gives some of the additionally assigned characters from the array.
#include <string.h>
using namespace std;
int main()
{
char *name = new char[10];
strcpy(name, "MoreThanTenCharacters");
cout << name << endl;
}
Although the allocated memory is for 10 characters, I can assign more. Printing gives exactly the same value. What is the logic behind it?
When the buffer pointed by the first argument is shorter than the string pointed by the second argument (taking the null terminator into consideration), then the copy will overflow the buffer into surrounding memory, and the behaviour of the program is undefined.
Printing gives exactly the same value. What is the logic behind it?
You've observed some behaviour. This is an example of possible behaviours that the program could have when the behaviour is undefined.
So, what is the correct way of allocating memory for JUST 10 chars and assigning a string to it?
Your allocation is correct although not ideal. Using a bare pointer is unsafe; in the end you leak the allocation. It's the copying where your bug happens.
An efficient and simple option is to use std::string. If your goal is to store the 10 character long prefix substring of the input, then following would be correct:
std::string name("MoreThanTenCharacters", 10);
This question already has answers here:
How to get the real and total length of char * (char array)?
(15 answers)
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 2 years ago.
Is there a way to determine the size of a char[] buffer via a char* pointer in C++? I'm using C++98.
The following lines of code all print out '8' (essentially sizeof(char*)). However I'm looking for the actual size of the buffer.
int maxBufferLen = 24;
char* buffer = new char[maxBufferLen];
std::cout << sizeof(buffer) << std::endl; // prints '8'
std::cout << ( sizeof(buffer) / sizeof(buffer[0]) ) << std::endl; // prints '8'
In practice, I am passing that char* buffer in between functions and I will not have access to the maxBufferLen variable that I am using to initialize it. As such, I'll need to determine the length using another way.
There is general no way of determining the size of an array based on a pointer to an element of that array.
Here are typical ways to find out the size:
Store the size in a variable
A variant of this is to store both the pointer and the size (or alternatively, pointer past the end) as members of a class. An example of this approach is the std::span class template (this standard class is not in C++98, but you can write your own, limited version).
A variant this, which is generally used when the array is allocated dynamically (such as in your example), is to deallocate the memory in the destructor of the class and conforming to the RAII idiom. Examples of this approach are std::string and std::vector.
Or choose certain element value to represent the last element of the array. When iterating the array, encountering this "terminator" element tells you that the end has been reached. This is typically used with character strings, especially in C interfaces, where the null terminator character ('\0') is used.
This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 9 years ago.
char *one = new char[1024];
char one1[] = "hello";
one = hello;
cout << sizeof(one) << endl;
I really want the last line to output sizeof(one1) but I know as it stands it will output the size of the pointer which is 4 or 8. Is there a way to extract the sizeof() of the array from just the pointer to the first letter?
Is there a way to extract the sizeof() of the array from just the pointer to the first letter?
No.
Unfortunately, you have to keep track of this explicitly and maybe pass around the length as extra arguments to functions etc.
You have tagged your question "C++". In C++ we usually use std::vector, std::string or other container classes to keep track of this.
There is no way to do this - maybe use a std::vector instead, or a std::string if you just need char's.
No.
That information is simply not available at run-time. A pointer is just a pointer, there is nowhere for the extra information (about the area being pointed at) to live.
#include <cstdio>
#include <iostream>
using namespace std;
int main ()
{
char buffer [1];
sprintf (buffer, "%d is one number", 1);
cout<<buffer<<endl;
return 0;
}
buffer's size is only one, but cout can print right result. Why?
Is it safe to do? Or I had to consider set one big size for buffer when using char * related methods?
No, it's not safe.
The C-style strings need to be null terminated, but there's not enough space in buffer. Undefined behavior doesn't mean guaranteed working or not working. When I tested your program, I got a segmentation fault.
As Yu Hao stated: It Is not safe!
But why is it working sometimes?
char buffer[1]
is not a managed array. It just gives the compiler the hint that he should reserve space for one char. the variable buffer is used as a pointer to that space and looses all information about the original size. so the above statement is the same as writing:
char bufferVar = '\0'; /* a single character */
char *buffer = &bufferVar; /* a pointer to bufferVar */
buffer just contains the address of a character but no other information at all!
your sprintf expects such an address an happy writes its string beginning at buffer.
The segmentation fault is a message from the Operating System. Your process allocates space for one byte. The OS manages your memory in pages (segments). When you cross a border of these segments a segmentation fault is raised.
As far as I know it depends on the compiler whether variable are allocated on the beginning or at the end of a segment.
Yu Hao's compiler obviously puts them at the end - yours at the front. So your sprintf doesn't write over the boundary of a segment.
Hope it helps.
As for considering the size needed to store a char * string, many of the C stdlib string functions will tell you the length they require if you pass them NULL. You can call this before allocating storage for the string to know how much storage you need:
std::cout << "You need a buffer that can store "
<< sprintf (NULL, "%d is one number", 1) + 1
<< " characters to safely store your string."
<< std::endl;
Another solution is to use something like snprintf (...), which guarantees that it will truncate the output so that it will not overrun your buffer:
snprintf (buffer, 1, "%d is one number", 1);
// ~~~
// Length of buffer
In your case, the buffer is only 1 character long so it only has enough space to store the null terminator; not particularly useful.
This question already has answers here:
What is the difference between char a[] = ?string?; and char *p = ?string?;?
(8 answers)
Closed 9 years ago.
What is the difference between C Style Strings
char str[10]="Hello";
char str[]="Hello";
char* str= "Hello";
1) I believe that char str[10]="Hello" is automatic variable and stored on the stack.True? i.e. Allocates 10 bytes on stack.
2) Does char str[]="Hello"; is also stored on stack? i.e. allocates 6 bytes - including null character on stack.
3) Does char* str= "Hello"; stores pointer str on stack and the object "Hello" is stored on heap? i.e. allocates 6 bytes - including null character on heap.
4) All strings (in question 1,2 and 3) are null terminated . True/False?
5) Whether it is C or C++ whenever we create an string like "Hello" , it is always null terminated. Suppose in C++ we declare string str = "Hello"; , is it also null Terminated?
EDIT
Consider All declared in main().
#Negative points and close requests. I am asking this question with respect to where they are stored heap or stack? And also null termination.
"Consider All declared in main()."
Then
1) Yes.
2) Yes.
3) Yes, and no (it's stored neither on the stack nor in the heap in common implementations). "i.e. allocates 6 bytes" -- you seem to have forgotten about the memory required for the pointer. Also, there's an erroneous claim in the comments and in another answer that char* str= "Hello"; is wrong, but in fact it is legal C and, for now, legal C++ ... see What is the type of string literals in C and C++?
4) True, but it would be false if you changed 10 to 5 -- that is, given char str[5]="Hello";, str is not NUL-terminated.
5) False and no (although the implementation might store a NUL following the string -- C++11 requires it -- but that isn't part of the string).
"I am asking this question with respect to where they are stored heap or stack?"
Where do people get the idea that these are the only sorts of memory? Local variables are stored on the stack and memory allocated via malloc or (non-placement) new is allocated from the heap. Program code, file-scope variables, and literals fall into neither of those categories.
You are looking at this kind of sideways, which is probably why you are confused ;-)
1) If these variables are all declared inside a routine definition, without the static keyword, then they are all on the stack.
BUT char str[10] and char str[] are arrays - you get all characters of the array on the stack.
char *str is a pointer to one or more characters. Only the pointer is sure to be on the stack.
2) "Hello" always represents a NULL terminated string in C - it's 6 char's long. If you wanted to initialize a character array to contain a set of characters which is not NULL terminated, you can't do it this way.
3) As people have pointed out in the comments, it's unclear what char *str = "Hello"; does, or even whether it's legal. If it were char const *str = "Hello"; and the compiler accepted it, I'd expect to find the 6 character string somewhere anonymous, global, and possibly protected.
4) I haven't a clue what the "string" class does in C++.