This question already has answers here:
Quick strlen question
(9 answers)
Closed 9 years ago.
I am writing simple function for merging two C-strings. While trying to dynamically alocate new chunk of memory i found out that :
char * out = new char[size];
std::cout << strlen(out) <<std::endl;
Returns 16 when size is 4 and 40 when size is 22 and so on.
Does anyone have an idea why it acts like that and how to allocate memory for c-string with certain number of chars?
The allocated memory is not initialized. strlen() just keeps charging through memory until it encounters a null character ('\0'). Since you have not initialized the memory pointed to by out, the contents of this memory are undefined, and therefore so is the behavior of strlen().
strlen() does not measure the size of an allocation, so your interpretation that new is allocating too much memory is incorrect simply because the tool you are using to measure the size of the allocation doesn't do that at all.
In your case, strlen() is reading beyond the boundary of this allocation. In this circumstance, the result could be a "wrong" value (as you see here) or your program could simply crash.
Using new to allocate memory does not initialize the memory:
char * out = new char[size];
// Add this code to initialize out
memset(out,'A',size-1);
out[size-1]='\0';
std::cout << strlen(out) <<std::endl;
Related
This question already has answers here:
What is the size of a pointer? [duplicate]
(8 answers)
Closed 6 months ago.
I want to add a string after the struct in memory.
How to check that i dynamically allocated right amount of bytes?
Example:
const wchar_t* add_str = L"test string";
struct test_{
wchar_t* name;
size_t namelen;
} test;
void* ptest_void = malloc(sizeof(test) + wcslen(add_str)*sizeof(wchar_t));
// i cant dereference void*, hence, cant check sizeof(*ptest_void)
// then i try to get sizeof of a ptr which was cast to (test_*):
test_* ptest = (test_*)ptest_void;
size_t ptest_sz = sizeof(*ptest);
// ptest_sz has the size of _test struct, but without size of add_str...
free(ptest_void);
sizeof(ptest) doesn't tell you how much allocated memory ptest points to. It tells you the size in bytes of the variable ptest, most likely either 4 or 8 depending on your system.
There's also no standard way to check "how big" an allocated block of memory it. You're expected to keep track of that yourself.
If a call to malloc does not return NULL, that means the call was successful, and you can access as many bytes as you told it to allocate.
This question already has answers here:
What is the difference between Static and Dynamic arrays in C++?
(13 answers)
Closed 1 year ago.
I have searched the web and found nothing regarding this..
char array[50];
char *array = new char[50];
Tell me the difference between them..
char array[50] is 50*sizeOfChar space allocated on stack.
char *array = new char[50] is 50 * sizeOfChar space allocated on heap, and address of first char is returned.
Memory allocated on stack gets free automatically when scope of variables ends.
Memory allocated using new operator will not free automatically, delete will be needed to be called by developer.
Mixing C/C++ is a nice though sometimes confusing:
char array[50];
Allocation on stack, so you don't need to worry about memory management. Of course you can use std::array<char, 50> array which being C++ brings some advantages (like a method which returns its size). The array exists until you leave its scope.
char *array = new char[50];
Here you need to manage the memory, because it is kept in the heap until you free it. Important, you should use this whenever you want to remove it:
delete [] array;
There also exist free(array) (Standard C) and delete (without parenthesis). Never use those, whenever you use new someType[...].
Other that in both you still have a char array of 50 elements you can play with :-)
This question already has answers here:
C++ new int[0] -- will it allocate memory?
(6 answers)
Closed 2 years ago.
// new T[0] allocate a zero sized array can have values?
auto pv=new int[0];
cout<<pv<<endl; //0x... ?
*pv=123;
cout<<*pv<<endl; //123 ?
delete[] pv;
Why?
if so, what's difference between new T[0] and new T[1]
Why can I set the value of 0 sized array ...?
It is legal to create a new int[0] (though at first glance it may not appear to be useful!).
However, your use of it is just like any other buffer overrun: your program has undefined behaviour.
C++ does not check array bounds for you. That's your job.
Going past them can appear to work; it can cause a crash; it can instantaneously transport the sun to another part of the galaxy.
Just don't do it.
This question already has answers here:
How dangerous is it to access an array out of bounds?
(12 answers)
Closed 6 years ago.
I would like to understand why this piece of code will not crash :
#include<studio.h>
#include<string.h>
main()
{
char *a;
a=(char *)malloc(1);
strcpy(a, "example");
}
I though we are writing to memory that is not the processes' since we allocate only 1 byte for the char * and we write more than that.
Can somebody please explain?
Thanks in advance.
Allocate enough space for the string.
#include <stdio.h>
#include <string.h>
int main()
{
char * a;
a = (char *)malloc(32);
strcpy(a, "example");
free(a); // don't forget to free
}
Explanation:
You allocated 1 byte you copied 7+1 (example + '\0').
You tried to access memory that was not allocated.
Read articles about buffer overflow.
Important:
If you are not aware of the input size (now we know "example" is 7+1 bytes)
you should use strncpy to specify the maximum number of bytes that can be copied.
There is a function strdup that duplicates the string. Same as allocation + strcpy.
Your allocator may allocate small chunks of fixed size for requests below certain threshold. I wouldn't be surprised you've got 8 bytes back, so strcpy works without crash
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 have the below code:
int* d = (int*) malloc(100 * sizeof(int));
cout<<"size of d which is pointer is: " << sizeof(d)<<endl;
I know that sizeof outputs 4 as d is a ptr. But, how can I find the sizeof the entire array using sizeof
You cannot - sizeof is a compile time operation and hence not dynamic.
As you are using c++ use std::vector instead. Otherwise create a structure to store both the pointer and the size of the array. Pass that around instead.
The pointer gives you the place in memory where your data is stored which is why you can't get it's size only from that information.
It's analogous to knowing how big my house is from knowing my address (without prior knowledge or the use of tools like Google Maps)
The direct ans. is no you can't but you can try this :
int x[]={1,2,3,4};
int *ptr=x;
decltype(sizeof(*ptr)) size=0;
while(*ptr<5){
size =size+sizeof(*ptr);
ptr++;
}
cout<<"Size is : "<<size;
Output:
Size is:16
You could argue that you already know the size of the entire array using sizeof - you've got it in your original malloc call - 100 * sizeof(int). Although the malloc machinery must know the amount of memory associated with the pointer internally (it needs it for a corresponding free call), and apparently some implementations provide functions to return this information, as far as I know there is not implementation-independent and portable way of doing this without handling it yourself.