Segmentation fault (Multi-dimensional array) [duplicate] - c

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 11 months ago.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i,j;
int (*a)[3]=NULL;
for(i=0; i<4;i++)
{
for(j=0; j<3;j++)
{
scanf("%d", *(a+i)+j);
}
}
for(i=0; i<4;i++)
for(j=0; j<3;j++)
printf("%5d", a[i][j]);
printf("\n");
return 0;
}
I have a problem with my C code above, which is trying to print a multi-dimensional array on screen. When running this code, a message of segmentation fault is sent to me and I don't know how to fix that.

The segmentation fault is due to the null pointer int (*a)[3]=NULL.
Either: allocate it dynamically (in this case, you have to free it when done with it):
int (*a)[3] = malloc(sizeof *a * 4);
or declare it static:
int a[4][3];
Also, you are missing some curly braces:
for(i=0; i<4;i++) { // This one
for(j=0; j<3;j++)
printf("%5d", a[i][j]);
printf("\n");
} // And this one

Related

How to avoid segmentation fault in C when the array is defined?

I have an array A1[ ]={1,0,1,1,..'X',0,1,'X',.1,0...}, as big as 10 Megas of binary integers and some 'X' values (taken as the ASCII integer value), I am thinking to use malloc but I already have the array defined (I am just copy and paste the values before running my code). Any other suggestions on how to avoid segmentation fault? So far this the error that I am geting :(.
The code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//int A[]={'x','x',1,0,'x',0,'x',1,1,1,...};//up to 10M values
int A[]={0,'x',1,'x',1,0,'x',0,'x','x',1,'x',0,'x','x','x','x','x','x',0};
int j;
#define n (sizeof(A)/sizeof(*A)) // bits
printf("Patt size= %d\n",n);
/*Code will be added here to make some calculations with A*/
printf("A ="); // show input
for(j=0; j<n; j++)
printf(" %d",A[j]);
return 0;
}

String matrix input output [duplicate]

This question already has answers here:
How can I correctly assign a new string value?
(4 answers)
Closed 5 years ago.
I want to make a matrix of strings in C Programming language
this is my code
void main()
{
char Data[10][3][20];
int i=0;
int j=0;
for (i=0;i<10;i++)
{
for (j=0;j<3;j++)
{
Data[i][j]="aa";
}
}
for (i=0;i<10;i++)
{
for (j=0;j<3;j++)
{
printf("%s",Data[i][j]);
}
}
printf("Done");
scanf("%d",&i);
}
the error am having is : assignment to expression with array type
please explain to me what am doing wrong because this is a prototype am trying to use in my original code that is to make a data base of "username,Password,level"
thank you inadvance.
Data[i][j] is an array. You can't assign to an array, only copy to it. use strcpy(). more details at http://www.cplusplus.com/reference/cstring/strcpy/
#include <stdio.h>
int main() {
char Data[10][3][20];
int i=0;
int j=0;
for (i=0;i<10;i++){
for (j=0;j<3;j++){
strcpy(Data[i][j], "aa"); //use strcpy for copy values
}
}
for (i=0;i<10;i++){
for (j=0;j<3;j++) {
printf("%s ",Data[i][j]);
}
printf("\n");
}
printf("Done");
scanf("%d",&i); //why this scanf here ??
return 0;
}
You are creating an array of char and you cannot assign (a pointer) to it. This is why you are getting the error assignment to expression with array type.
You can copy the string to the array elements though. Try using strcpy instead of the below assignment in your code:
Data[i][j]="aa";

Segmentation fault in my program

My sorting program results in a "segmentation fault 11":
#include <stdio.h>
int main()
{
// Asking user for number of inputs in an array
int n;
do {
printf ("enter the number of intigers you want to sort\n");
scanf("%d",&n);
}while (n<=1);
int sort [n];
printf ("please enter %d numbers\n",n);
for (int i=0; i<n; i++) {
scanf("%d",&sort[i]);
}
printf("you entered\n ");
for (int i=0; i<n; i++) {
printf(" %d ",sort[i]);
}
printf("\n");
int k,c,i,x;
for (i=0;i<n;i++) {
if (sort[i]<sort[i-1]){
k=i-2;
while (sort[k]>sort[i]){
k--;
}
k++;
x =sort[i];
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
}
}
printf ("Sorted numbers :-\n");
for (int i=0; i<n; i++) {
printf ("%d ",sort[i]);
}
printf ("\n");
return 0;
}
Now I have looked up the internet and found that it is caused because a variable has value that exceeds the system's memory limit. But cannot understand that concept.
for (i=0;i<n;i++)
{
if (sort[i]<sort[i-1])
You are accessing array out of its bounds.Maybe you want to start your loop from 1.Also
k=i-2;
while (sort[k]>sort[i])
will access index beyond 0 for example if i is 0 or 1 or 2
k = i - 2; looks unstable for low values of i.
sort[i - 1] is undefined when i is zero.
The thing causes the behaviour of sort[k] to be undefined.
Moral of the story: check all the array indexes before attempting to retrieve an array element. Your debugger will help you here.
In addition to all said before:
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
i can be 0 -> c can be 0 -> sort[c-1] would also result in accessing array out of bounds.
There is no need to initialize c=i twice. It is enough to do it in the loop-declaration

array used uninitialized in this function

My task is to allocate memory for an array of integers (n elements), to give random values to each one of them and to print them sorted and unsorted. When I compile the code, I get this warning "'v' is used uninitialized in this function", and when I try to run it, I get "Segmentation fault".
I was wondering why am I supposed to initialize the array if I want to fill it up with random values? Is there a problem in the way I allocate memory for the array?(I'm not sure about the cast i did)
This is the source code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
int i, j, max, n, *v, aux;
scanf("%d%d", &n, &max);
*v=(int*)malloc(n*sizeof(int));
for(i=0; i<n; i++){
srand(time(NULL));
v[i]=rand()%max;
}
for(i=0; i<n; i++){
printf("%d ", v[i]);
}
printf("\n");
for(i=0; i<n-1; i++){
for(j=0; j<n-i-1; j++){
if(v[j]>v[j+1]){
aux=v[j];
v[j]=v[j+1];
v[j+1]=aux;
}
}
}
for(i=0; i<n; i++){
printf("%d ", v[i]);
}
printf("\n");
return 0;
}
I would be grateful if someone could make me understand what I do wrong, and eventually modify part of the source.
You made a typo (I presume) when creating the array.
*v=(int*)malloc(n*sizeof(int));
should be
v=(int*)malloc(n*sizeof(int));
The warning
'v' is used uninitialized in this function
is because of the deferencing *v in the line above.
Here's your problem:
*v=(int*)malloc(n*sizeof(int));
You assign the address of your allocated memory to the dereference of v - that is, you dereference your uninitialized pointer, and write to "wild memory".
In addition, using unitialized values is still a rotten way to get randomness. Look up rand() in your manual.

2D array - sorting | Access violation reading location error | In C

Hey guys I am trying to finish my code but instead of getting values i am getting an error msg
.when i am about to enter lien number 54 or 60.
if(*arr[rows*columns]<num) or printf("Number value %d in a two-dimensional size is:%d\n",num,*arr[num]);
This is error msg.
Unhandled exception at 0x013137b2 in LB_12.exe: 0xC0000005: Access violation reading location 0xabababab.
Mission description and the error msg int he next picture.
what is wrong? i have to create another array and copy the values if i want the program to print the values?
This is my code
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void SortArray(int **arr,int rows,int columns,int num);
void freemalloc ( int **arr,int rows);
void main()
{
int **arr;
int i,j,rows,columns,num;
printf("Please enter the size of 2D array(rows ,cols)");
scanf("%d %d",&rows , &columns);
arr=(int **)malloc(rows*sizeof(int *)); // Allocate array of pointers
if(!arr) // Terms - if there is not enough memory,print error msg and exit the program.
{
printf("alloc failed\n");
return ;
}
for(i=0; i<rows; i++)
arr[i]=(int *)malloc(columns*sizeof(int)); // Allocate memory for each row
printf("Please fill the 2D array\n");
for(i=0 ; i<rows ; i++)
{
for (j=0 ; j<columns ; j++)
{
printf("row:%d columns:%d\n", i,j);
scanf("%d" , &arr[i][j]);
}
}
printf("Please enter a postive number: ");
scanf("%d",&num);
SortArray(arr,rows,columns,num);
freemalloc(arr,rows);
system("pause");
return;
}
void SortArray(int **arr,int rows,int columns,int num)
{
int i,j,temp;
for(i=0 ; i<rows ; i++ ) // Bubble sort for sorting the 2d array
{
for(j=0 ; j<i-1 ; j++ )
{
if(arr[i][j]>arr[i][j+1])
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
}
if(*arr[rows*columns]<num)
{
printf("No solution,The maximum value is:%d\n",arr[rows*columns]);
}
else
{
printf("Number value %d in a two-dimensional size is:%d\n",num,*arr[num]);
}
}
void freemalloc ( int **arr,int rows)
{
int i;
for (i=0 ; i<rows ; i++) // Loop for free the array of pointers
{
free(arr[i]); // free each seprate row
}
free(arr);
}
My guess is that rows * columns is larger than what you have allocated, meaning you try to dereference a random pointer, leading to undefined behavior and causing the crash.
Also, you will never sort anything, as the outer loop condition is always false (try changing > to <).
My bet is :
printf("Number value %d in a two-dimensional size is:%d\n",num,*arr[num]);
You're asking for some number and put it in variable num. What makes you think that number num is first number in num-th row?
There might be, and propably are more problems with this code.
EDIT:
*arr[num] is evaluated from right to left. [] have higher precedence than * operator.
So it first does arr[num]. and result of that is dereferenced *(arr[num]). num is treated like a row, so if you don't have enough rows-you got memory violation because you are beyond array

Resources