I am trying to concatenate char* and const string but the system hangs. following is the code
unsigned long long size = 2*pow(10,18);
char* string = malloc(size);
strcat(string," ");
I am not sure how to resolve the error. Using Dev c/c++ in windows 10.
Edit: Thank you for all your comments and answer. I have made the change in my code. But it still gives the same problem. It does not print the statement and still hangs.
char* string = malloc(20*sizeof(char));
if(string=NULL){
printf("unsuccessful memory allocation");
}
strcat(string," ");
The most probable reason might be that malloc()
might fail to allocate the amount of memory you request for . Always check if the memory is successfully allocated or not this way :
char *p; //some pointer
p=malloc(size*sizeof(char));
if(p==NULL)
{
printf("unsuccessfull memory allocation");
exit(1);
}
Note :
malloc()
returns the address of newly allocated memory on successful allocation .- if memory allocation is not successful then, it returns
NULL
And as @BLUEPIXY has mentioned in the comments, your strcat()
will fail even if allocation is successful,
try initialize the string
before using :
*string = 0;
or copy string
before strcat()
function.
You are trying to allocate 20000000TB. You certainly don't have that much memory. malloc will be failing and returning a NULL pointer which you are then trying to write to!
I think that the cause of the fail is the size of memory you are trying to malloc.
unsigned long long size = 2*pow(10,18);
char* string = malloc(size);
you are trying to malloc: 2000000000000000000 bytes
Thats 2 EB (EB: exabyte) 1 EB = 1000000 GB
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.