Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've spent quite a moment today trying to figure out why a super-simple C function, which reads a text file, doesn't work. I was able to make it work by swapping parameters in calloc function:
Instead of:
calloc(1, size_of_the_memory_to_allocate)
I did:
calloc(size_of_the_memory_to_allocate, 1)
So instead of 1 element of size 20, I did 20 of size 1.
calloc(size, 1)
Is there any difference in the allocation?
EDIT2:
I guess I was not clear enough with the question, or it was misunderstood. The question was: "Why allocating pointer to pointer using calloc requires swapping arguments?". It wasn't about debugging the code, nor have I asked anyone to run it, it was about how calloc works. The answer made by #chqrlie is exactly what I was looking for. I guess I have made a mistake of adding any code to the question, and readers concentrated on it, rather than on what I have asked for. So, here's an edit, and now chqrlie's answer fit perfectly. If this still is something that won't help other users, let's just delete the question and be done with it.
The prototypes for calloc and fread are:
void *calloc(size_t nmemb, size_t size);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
The order of arguments is indeed inconsistent between these standard C library functions. It is unfortunate but it has been like this for close to 40 years and cannot be changed now.
Note that if you swap the arguments in calloc, you should get exactly the same behavior, but it is not the case for fread that returns the number of elements completely read.
The behavior you describe in your updated question is highly surprising. Either there is something you are not telling us, or your C library implements a non standard constraint in calloc() that ends up backfiring into a bug.
Note that calloc(nmemb, size) cannot just call malloc(nmemb * size) because of potential arithmetic overflow, which in the case of size_t arguments is defined in the standard. For example calloc(-1, -1) must fail, but instead would return malloc(1) if naively calling malloc(nmemb * size). The test for this overflow might be buggy in such a way as to fail for calloc(1, size) and not for calloc(size, 1) with a large size.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need something like strlen but the string is filled with only null-terminators "\0\0\0\0\0\0\0" and I need to fill it with another character up until (not including) the last \0 like so "FFFFFF\0". Is there a way to calculate the size without errors?
I had to implement bzero for a school project called "libft". Then I was tasked with implementing strcpy and I saw in the man pages that dest needs to be large enough to receive the copy of src so I want to account for a situation where bzero was used on dest and strcpy doesn't allow me to pass the size of dest as a parameter. I was just wondering (out of curiosity) how I would know how big dest is because I know that strcpy does not account for this. There is a warning in the man page "Beware of buffer overruns! (See BUGS.)".
I realise now that this might be impossible in C.
What you're asking is whether you can know how much memory has been allocated.
If it was allocated with malloc, no.
If it's an array allocated on the stack, like char foo[10], yes you can use sizeof(foo), but that doesn't tell you anything you didn't already know.
If you need to know the allocated size of the string, you need to remember it at allocation time and pass it around. You can use an extra variable, or you can make a struct which has both the string and size.
No, there is no generic way. If your char * input fulfils *input == '\0', then it is a null terminated string of size zero, and we cannot know whether input[n] is valid for any n > 0.
However, if you had control over the allocation of input or any other hint, you can use that information, e.g.
input = malloc(N);
/* use N */
Otherwise, it's completely opaque.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So I ran into an issue where it seemed like realloc wasn't copying all of the data in a buffer so I decided to run the following code as a test.
#include <stdlib.h>
int main(int argc, char** argv)
{
int* tmp_array = malloc(sizeof(int) * 2);
tmp_array[0] = 1;
tmp_array[1] = 2;
tmp_array = realloc(tmp_array, 4);
return 0;
}
The same issue I originally had was still happening, only part of the data is being copied. The 1 in the buffer gets copied, however the 2 does not. I am allocating enough space for 2 integers at first so both if the assignments to tmp_array should be valid. Then reallocating to 4 seems valid. I even tried explicitly casting the returned realloc pointer to int* but that didn't help.
Unfortunately, I can't show the screenshots of my memory window in the debugger (VS 2017) but it definitely shows the 1 and 2 in the buffer before realloc and only shows the 1 in the buffer after the realloc.
I'm sure I could reimplement realloc myself by just using malloc and memcpy to copy the data over manually, but I still just want to know why this isn't working.
Any help is greatly appreciated!
You are reallocating to 4 bytes, not to 4*sizeof(int), which incidentally copies just first int (and discards other).
realloc, as malloc, works on bytes so you must use them both in the same way.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to inject executable code in memory using C. The executable should be able to read it's own code and copy it to some other location referenced by a pointer. The general template code is as follows
int
main(){
int (*main_ptr)();
main_ptr=main; // make the pointer point to start of main
/*
* rest of the code.
*
*/
/*Now I am trying to print the first 10 bytes of the main function.
* just to see if it is possible to access main's code.
*/
for(int i=0;i<10;i++)
printf("%x ",*main_ptr++);
return 0;
}
but the output is the value of the pointer (i.e. address of main function), not the value to which it points (the code of the main function). I had read somewhere that C does not dereference function pointers. But I do not know why. Is there a way to get around this?
Or, is there another way for a program to access its own code section?
P.S. I understand that many may think this is a stupid question and does not contribute significantly to research and all that. But I'am trying to understand how malware is written and given the absence of material on the web, it has been frustrating, so I decided to try this myself. Any help would be great.
There are 2 issue with your code (even though as such it is UB to be strict).
But even from any implementations point of view there are the following issues
None of the implementations define the * operator for function pointer.
None of the implementations define the ++ operator on the function pointers because size of a function is not defined.
But most implementations do define casting a fptr to void* and then to other data pointers even though it is UB.
You can make use of that fact.
I tried the simple modification of your code -
for(i=0;i<10;i++)
printf("%x ",*((int*)main_ptr++));
And it produced the "expected" behavior with gcc (MinGW64), compared the output against objdump.
Finally this goes with the warning that none of the approaches are portable. Perhaps there is no portable way to achieve what you are doing.
If you just have to get the same code as main, one way could be to read the actual binary (pointed by arg[0]). Parse the headers to find main and then read the bytes from there. Since reading the file would give you a data pointer there is no UB there.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am running into a segmentation fault error in my code and I am not sure what may be causing it. What is even more odd is that when I run I compile/run in gcc-4.4.6 RH6 I obtain no error, but on other compilers/linux distros I get a segmentation fault error.
Here is a snippet of the part of the code that I think may be generating the issue:
int BIN_SIZE=(2*width)/bins;
//binCounts and binCounts2 store the fragment counts in each bin. mask=1 flags histone modification site
float **binVals;
binVals = (float **)malloc(chromNum*sizeof(int *));
//Initialize the arrays
totalBinNum = 0;
for (i=0;i<chromNum;i++)
{
totalBinNum += chromInfo[i].chromSize/BIN_SIZE+1;
binVals[i] = (float *)malloc((chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
memset(binVals[i], 0, (chromInfo[i].chromSize/BIN_SIZE+1)*sizeof(float));
}
If you know some easy catch on what may be causing the error please let me know? Otherwise it could also be in some other part of the code leading to not a smart Q :(
It would be more precise to do so:
binVals = malloc(chromNum*sizeof(float *));
But it is not likely that this is the cause of the error, as you can expect that 2 pointers, even if to different types int* and float*, will have the same size. In short, the source of the error is probably somewhere else in your code.
Some other suggestions:
I would suggest removing the other type cast in the other malloc.
I would use some temporary variable to store chromInfo[i].chromSize/BIN_SIZE+1, so that you do not have to repeat the expression 3 times with very likely cut and past errors.
You can compact the malloc and the memset to zero in one calloc call.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I pasted my code here: http://pastebin.com/tPvRHrkW
Compiled with gcc.
It seems the error occurred because I defined a struct too big for the compiler. I took the struct out into another single source file and tested it, no error occurred this time. So why am I getting SIGSEGV and is there any limit on the size of a struct?
There isn't a limit to the size of the struct, the problem is with how you're using it. MGraph is the huge structure type, and in two places you're using it in a manner that places it on the stack; once as a parameter to a function and again as a local variable. Stack space is often not something that is permitted to grow to huge proportions.
I would suggest two changes. First, use dynamic allocation for instances of this type. Second, pass pointers as parameters to it, rather than the actual data.
Generally you're only limited by available memory and the addressing capabilities of your system. However in your case you're declaring a local variable, which will be allocated on the stack. The stack is likely much more limited in capacity.
#define MAXV 20000 .. int edges[MAXV][MAXV];
is 20000 * 20000 * 4 ~ 1.5 Gigs of memory on stack.
You should probably use malloc & dynamically allocate instead.