Exception has occured. Segmentation Fault [closed] - arrays

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 22 days ago.
Improve this question
I am getting this segmentation error and I can seem to find where it is occuring. I am trying to create a list of float values through an array of floats. It is one of my assignment from college class.
my code
I have tried to comment out the float array all together to see if that is where the error is occuring but it seems the error always happens after scanf and it asks for a user size of the array.

The code segfaults because scanf() expects a pointer to store the data that was read.
In your case scanf("%d", size); with size initialized to 0 (see size = 0) means scanf should store the data at address 0 which is an invalid pointer to write and read from (NULL pointer).
However, it doesn't really matter that you're trying to write to a NULL pointer, any other fixed pointer would most likely cause a segfault too (i.e. if size were 2 or 242353252 it would still segfault). Segfault simply means your program accessed an invalid memory location ; and there are A LOT of invalid memory locations that could be accessed by your program.
That's why your program segfaults.
To get the address of a variable use the & operator:
scanf("%d", &size);
Now scanf receives the address of whatever address size is stored at.
scanf("%d", &numList[i]);
Is also wrong, but for a different reason: %d expects an int variable, but you're passing the address of a float variable.

Related

Two format specifiers but only one argument [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 5 years ago.
Improve this question
#include<stdio.h>
int main() {
int j=65;
printf("j>=65?%d:%c\n",j);
return 0;
}
Ok it is understood that in place of %d ,value of j will be printed but why %c is replaced by ö ,i am unable to understand the output of this program , explain the printf statement.
You put doublequotes in a wrong place: you quoted the entire expression, rather than making your format string a conditional:
printf((j >= 65 ? "%d\n" : "%c\n"), j);
Your j >= 65 ? ... : ... expression is part of the string literal. C compiler does not "see" it as anything related to j. Hence the format string contains two format specifiers, with a single printed item; that's undefined behavior.
UB manifests itself in different ways; on your particular system a junk character 'ö' gets printed. This, however, is not a guaranteed behavior - on other systems you may get a different output, or a crash. See this Q&A for an explanation of UB.
This is enough I suppose for explaining whatever you have shown. And the behavior you see can be anything given that it is undefined.
From standard
The fprintf function writes output to the stream pointed to by stream,
under control of the string pointed to by format that specifies how
subsequent arguments are converted for output. If there are
insufficient arguments for the format, the behavior is undefined.
Emphasis mine.
The short answer for this is that this is undefined behavior, the character that gets printed could be anything and the program may even crash.
The longer answer is that old compilers did not check printf strings against the arguments passed, and so by default compilers to not treat this as an error. If you enable the correct warnings (-Wformat) it will complain about this at compile time, and with -Werror the warning will be escalated to an error. Because this is not checked at compile time, as many arguments as are needed are fetched from where they should be on the call stack. This means that first argument after the last specified argument probably has to do with the return address for the stack frame or something, but after that you start to push into unallocated memory. Either way, the behavior is undefined.
If you're interested in more details, this stack overflow answer explains it well.

Malloc returning zeroed memory as output [closed]

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 6 years ago.
Improve this question
I am using the below mentioned to simply learn about malloc. As I have heard and studied that malloc allocate an unintialized storage for you. So the output of this program should be a garbage value. But I am getting 0 as the output. Please tell me what is wrong here?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *x =(int*)malloc(100000000*sizeof(int));
printf("%d",x[0]);
return 0;
}
OUTPUT 0
If malloc returns a null-pointer, and you dereference this null-pointer, you have undefined behavior.
If it doesn't return NULL, then the contents of the memory is indeterminate and using it in any way without initialization is still undefined behavior.
But to explain your behavior, if you get a non-null pointer back, then one of the possible value of the indeterminate values is zero. If you get a null-pointer back, then you might a well might had a crash instead of printing a zero.
Also, some environments might initialize memory to certain values when debugging. Clearing everything (i.e. setting most or everything to zero) is common when running in a debugger
That's the problem with garbage (as well as with undefined behavior) — it could be anything. And among the behaviors that fall under the category of "anything" is looking like it's doing something sensible.
(P.S. you should also test the return value of malloc; errors can happen, and it will signify the error by returning a null pointer)
You are printing the contents of storage with an indeterminate value. This is undefined behaviour. Anything can happen. Some of the things that can happen is the application crashing, your washing machine starting to wash, or your computer printing the number zero.

Should I always allocate arrays dynamically, just to be safe? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I was writing a simple program and created an array to store 4 integers. Then I used a for loop to assign them; right after that I used the gets() function to get a string; after using the gets() function the first integer on the array would always become a 0. I even printed the variable on the screen before and after the gets() to confirm.
The only thing that fixed it was dynamically allocating the array, so now I want to know if I should always allocate arrays dynamically to prevent this kind of issue?
code:
int nums[4];
int i = 0;
char symbols[3];
for(i=0;i<4;i++){
scanf("%d", &nums[i]);
}
fflush(stdin);
gets(symbols);
calculate(nums, symbols);
No, you should not.
You should allocate arrays dynamically if you don't know their size at compile-time.
If you know the size at compile-time, allocate it statically.
In both cases you should think twice about the size - e.g. if you forget about the '\0' at the end of a C-String you will end up writing in memory you didn't allocate.
In your program, the problem is that you use gets() which is unusably dangerous. It almost certainly overflowed your string, leading to undefined behaviour. In your program, the undefined behaviour manifested itself as an unexpected change to the array of integers. Using dynamic memory allocation changed where the array was stored compared to the string; it changed the undefined behaviour, but didn't fix the problem (which is that you overflowed your string buffer and invoked undefined behaviour when you did so).

Segmentation fault error when compiler with one gcc compiler but not with other gcc compilers [closed]

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.

Why is my 2D Array code working with malloc(0)? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have weird problem: my code is working. Specifically this is working. Why?
char **array = malloc(0);
array[0] = malloc(0);
strcpy(array[0],"hello");
array[1] = malloc(0);
strcpy(array[1],"world");
What the hell is going on? When I replace any of the mallocs with NULL or remove them
it doesn't work but it doesn't seem to matter what value is inside malloc granted it's
not negative.
Dereferencing an invalid pointer is an undefined behavior; so anything can happen.
malloc(0) is implementation-defined and returns either a null pointer or an invalid pointer.
You are invoking undefined behavior by using the pointer returned by malloc(0).
Besides the undefined behaviour of malloc(0). Malloc implementations often have a minimal granularity for the allocated blocks for alignment reasons. Which means that any block will always have at least a size of 4, 8, 12, 16 bytes, depending on implementation. If I remembered correctly, you can even set this value with a mallopt call on certain platforms.
The other thing is, that buffer overflows in allocation code often only crashes when you try to free the pointer(s), because only then is the memory around your block used for internal book keeping used by the library. That's one of the reasons why buffer overflows are so difficult to catch, they manifest at different locations and times then when they occured.

Resources