Segmentation fault in scanning values in Dynamic array ( int **arr) - c

This code Giving a segmentation fault. On debugging by GDB it is giving this error:
"Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7a6dde5 in _IO_vfscanf_internal (s=,
format=, argptr=argptr#entry=0x7fffffffdba8,
errp=errp#entry=0x0) at vfscanf.c:1902 1902 vfscanf.c: No such file or directory. "
void readData()
{
int **arr,m;
scanf("%d",&m);
arr = (int **)malloc(sizeof(int)*m);
for(int i=0;i<m;i++)
{
arr[i] = (int *)malloc(sizeof(int) * 2);
}
for(int i=0;i<m;i++)
{
printf("..%d ..\n",i); // if m = 20 then running only 12 times
scanf("%d %d",&arr[i][0],&arr[i][1]);
}
}
int main()
{
readData();
}
If m=20 then, Second loop is only running 12 times and then giving segmentation fault. While first loop is running 20 times.
Please Help me out.

arr = (int **)malloc(sizeof(int)*m);
This should be
arr = malloc(sizeof(int*)*m);
since you need to allocate m pointers, not m ints. Or better,
arr = malloc(sizeof(*arr)*m);
(By the way, don't cast the result of malloc.)

Following line has a problem
arr = (int **)malloc(sizeof(int)*m);
you are allocating sizeof(int) times m, this should be changed to sizeof(int *)*m to hold addresses rather than int (these might be of different sizes and can cause problem). So this should be as below
scanf("%d",&m);
arr = (int **)malloc(sizeof(int *)*m);
for(int i=0;i<m;i++)

Related

Segmentation Fault in C when adding an element to array

I am trying to calculate result of the floor function for floats <= 9999.
#include <stdlib.h>
include <stdio.h>
#include "string.h"
int main(int argc, char* argv[]) {
int i, j, k;
int x[1000];
for(i = 0; i < 10000; ++i){
x[i] = i;
}
printf("Enter a float in 0..9999: ");
scanf("%d", k);
tester(x, k);
}
int tester(int* c, int k) {
printf("x[%d] = %d\n", k, c[k]);
}
When compiler came to;
for(i = 0; i < 10000; ++i){
x[i] = i;
}
it gives segmentation fault;
x[i] = i;
here.
I have already checked similar questions about assigning segmentation fault but I couldn't find any solution way. Can anyone help?
The array x is of length 1,000, but you're treating it in the loop as if it's of length 10,000. Accessing x[i] for i greater than or equal to 1,000 is undefined behaviour because the index is out of the array's range.
Thus, a segmentation fault is occurring because your program is accessing memory that it is not allowed to access.
The variable k is initialised and when getting input "&" is missing in the scanf statement. This might have come under segmentation fault since the value "k" is passed in the function tester(). Generally in C lang, we get input with "&", unless if it is a string you don't necessarily mention that in the scanf statement!!.

c programming encounters Segmentation fault (core dumped)

I am trying to allocate a big block of memory.
I ran this code firt,
#include <stdio.h>
#include <stdlib.h>
int main()
{
long i;
long n = 50000;
printf("trying to malloc %ld memory. ", n);
long *ptr;
ptr = (long*) malloc(n * sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
for(i = 0; i < n; ++i)
{
*(ptr+2*i) = 9;
}
for(i = 0; i < 5; ++i)
{
printf("%ld ", *(ptr+2*i));
}
return 0;
}
and then I got this error
Segmentation fault (core dumped)
I know this "you are accessing memory that does not belong to you.", but why
PS:
long n = 5000; works well
When you have a pointer to a datatype, adding 1 to that pointer will actually offset the address by however large the datatype is. If I have a pointer to an integer array at 0x0000, doing myArray += 1; will result in my pointer having the value of 0x0004 (assuming an integer is 4 bytes on my system)
Knowing this, you can see how the line *(ptr+2*i) will go out of the bounds of your array for all values of i greater than i/2
Normally, since you are dynamically creating this array, writing to these addresses would just corrupt heap memory and not cause a segfault. The problem is that your program is going so far out of bounds, it is past the heap and going into memory that doesn't belong to your program. This is why it segfaults for 50000 and not 5000.

Program in C randomly crashes when I use free()

This program is supposed to allow the user to type in as many variables as they would like (which is stored in an array). Once the user types in "-999", the program will stop filling the array, find the largest number in the array and end. However, when I input some test numbers into the program, it will successfully end at times, but other times it will just decide to crash.
For example, I could type in:
100 (return) 200 (return) 300 (return) 400 (return) -999 (return)
and it will crash.
Then I'll type in:
10 (return) 20 (return) 30 (return) 40 (return) -999 (return)
and it will run successfully. Then if I type what I typed originally it will work and won't crash. And I'll even repeat this test and it won't replicate the same results.
I'm totally confused and lost, any help would be appreciated.
#include <stdio.h>
void fillArray(int *a);
int largestElement(int *a);
int i = 0;
int main()
{
int *array = (int *)malloc(sizeof(int));
fillArray(array);
printf("The largest element in 'array' is: %d\n", largestElement(array));
//Program randomly crashes right here sometimes, not sure why.
printf("Right before free function...\n");
free(array);
printf("Successfully freed!\n");
return 0;
}
void fillArray (int *a)
{
int userInput = 0;
printf("Type in a list of numbers terminated by a -999:\n");
while(userInput != -999)
{
//*a = realloc(a, (i+1) * sizeof(int));
scanf("%d", &userInput);
a[i] = userInput;
i++;
}
}
int largestElement(int *a)
{
int j;
int largest = a[0];
for(j = 0; j < i; j++){
if(a[j] > largest){
largest = a[j];
}
}
return largest;
}
The reason for the crash on free is because you only allocate space for a single int, but you copy values into a as if it's an array with multiple values. Writing past the end of allocated memory like that invokes undefined behavior.
The call to realloc you have commented out isn't quite doing what you want:
*a = realloc(a, (i+1) * sizeof(int));
The expression *a is of type int, do it doesn't make sense to assign a pointer back to it. Because realloc can move the memory that was originally allocated, you need to pass the address of array in main so that it can be modified in the calling function.
So change fillArray to take a pointer-to-pointer:
void fillArray (int **a)
{
int userInput = 0;
printf("Type in a list of numbers terminated by a -999:\n");
while(userInput != -999)
{
*a = realloc(*a, (i+1) * sizeof(int));
scanf("%d", &userInput);
(*a)[i] = userInput;
i++;
}
}
And call it like this:
fillArray(&array);

Getting segmentation fault while printing output

I am trying to know how the array in c is working. so i was implementing some basic array concepts. when i run the program i got the exact output but at the end of the output it says segmentation fault.
int main(void)
{
int a[] = {};
printf("Enter the number:");
int n = get_int();
int m = 0;
for(int i = 0; i<n; i++)
{
printf("insert:");
m = get_int();
a[i] = m;
}
for(int j = 0; j < n; j++)
{
printf("%d\n", a[j]);
}
}
output:
Enter the number:3
insert:1
insert:2
insert:3
1
2
3
~/workspace/ $ ./arr_test
Enter the number:5
insert:1
insert:2
insert:3
insert:4
insert:5
1
2
3
4
5
Segmentation fault
see for the first output it has a size of 3 it doesn't show segmentation fault but for second one it has a size of 5 it shows. so why its happening and what mistake i made.
You need to allocate memory for the array. Something like:
int main(void) {
int *a;
...
int n = get_int();
...
a = malloc(n * sizeof(int));
if (!a) {
// Add error handling here
}
...
}
If you know the size of the array you want to make ahead of time, declare it like int a[128]; instead of just int a[]; so a at indices 0 to 127 will be safe to write to (and subsequently read from).
If you want to declare an array of size n at runtime, use int a[] = malloc(n * sizeof(int)); or int *a = malloc(n * sizeof(int));. Make sure a is not NULL before using it, and remember to call free(a); when you are done with it to avoid a memory leak.

Segmentation Fault when accessing global integer array

I am writing C code to take user parameters and build an integer array from them. I ask the user to provide the array length and each element's value.
Running the following code causes an error at the printArray() function call. Following the debugger into printArray(), the Segmentation Fault itself occurs at printf("%d", intArray[i])
NOTE: The array is correctly printed when I copy the printArray() code into main() instead of making a function call. This makes me think that I have an issue with global variables and/or pointers. I am still learning C, so your guidance is appreciated.
How can I fix this? See debugger output at the bottom for more info.
void printArray();
int arraySize;
int* intArray;
int main() {
printf("Enter array length:\n");
scanf("%d", &arraySize);
int* intArray = (int*) malloc(sizeof(int)*arraySize);
printf("Enter an integer value for each array element:\n");
for (int i = 0; i < arraySize; i++) {
printf("Enter element %d:\n", i);
scanf("%d", &intArray[i]);
}
printArray();
return 0;
}
void printArray() {
printf("[");
for (int i = 0; i < arraySize; i++) {
printf("%d", intArray[i]);
}
printf("]\n");
}
I think you have redeclared intArray variable in main()
int* intArray = (int*) malloc(sizeof(int)*arraySize);
by doing this, the scope of this variable is only in the main function and printArray() does not know about this definition. So printArray() tries to access intArray variable which you have declared globally(which does not have definition) and thus leading to segmentation fault.
So just give intArray = (int*) malloc(sizeof(int)*arraySize);

Resources