Answer the question
In order to leave comments, you need to log in
Why clogged cpu when executing a program?
A program has been written that gives the result, followed by the lines
free(ptr[0]);
free(ptr[1]);
free(ptr[2]);
free(ptr);
// sometimes I can't get here. the program sometimes stops being processed (percent is clogged)
_getch();
return 0;
why?
Answer the question
In order to leave comments, you need to log in
Dmitry Korolev, The error is at least here:
ptr = (char**)malloc(3);
Immediately caught my eye.
What makes you think that the pointer has a size of 1 byte.
If anything, the size in bytes of memory to be allocated is passed to malloc.
You have an array of three elements, each element has a size: sizeof(*ptr)
Calling malloc should be like this:
ptr = (char**)malloc(sizeof(*ptr) * 3);
This is how strings are not assigned in C:
ptr[0] = "1001.01\0";
ptr[1] = "11.1\0";
If you need to copy these lines into the buffer that you allocated with malloc calls for ptr[0] and ptr[1], then you need to use memcpy:
memcpy(ptr[0], "1001.01", 7 );
And at the end of string literals, you do not need to force \0 - it will be automatically set there by the compiler, you just need to take into account the presence of this 0 at the end of lines.
Like this:
ptr[0] = "1001.01\0";
ptr[1] = "11.1\0";
you lose the buffer allocated above by malloc and then pass the address of the constant to free, which goes crazy with this fact :-)
Actually, my assumption was confirmed in the first post.
yes, for strings, not memcpy, but strcpy is better.
But memcpy will do the same thing, it's just that strcpy is focused on working with strings, it determines the end of copying by the \0 character at the end of the input string.
memcpy is more versatile, it can copy any piece of memory, you just need to take care of passing the correct size to the function.
res2001
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question