Segmentation Fault return in C [closed] - c

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
Program compiles fine, but returns 'segmentation fault' when ran. Please help. thanks. Ignore the other three functions. The program should Fill an array and the print the value in the array, using pointers and pointer arithmetic
#include <stdio.h>
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
//void BubbleSort ( int *array, int size );
//void SelectionSort ( int *array, int size );
//void Swap ( int *x, int *y );
#define SIZE 20
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i<100; i++)
{
printf("%d \t", *(array+i));
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i<100; i++)
{
*(array+i)= rand()%101;
}
return;
}

Your array contain only 20 entries but you tried to access invalid entries whose indexes were from 20 to 99.

You are trying accesing out-of-bound elements. Here is a quick fix:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i<100; i++)
{
printf("%d \t", array[i]);
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i<100; i++)
{
array[i] = rand() % 101;
}
}

You are trying to access out-of-bound elements. Here is the right way to do it.
Although you pass size of array as another argument, instead of using it, you're using a larger size of 100 which is hard coded.
#include <stdio.h>
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
#define SIZE 20
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i < size; i++)
{
printf("%d \t", *(array+i));
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i < size; i++)
{
*(array+i)= rand()%101;
}
return;
}

Related

Dice experiment, increasing maximum amount of throws

I was building a simple program to count the frequencies of the numbers in a dice experiment, but I tried to expand it and increase the maximum amount of throws to huge numbers, and by trial and error I found the max limit to be 519253.
With this maximum value I can’t create any new arrays either, it crashes.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MX 519253
#define DICE 6
void throwdice(int n[], int size);
int genNum();
void printv(int n[], int size);
void countd(int n[], int size, int count[DICE]);
int main ()
{
srand(time(NULL));
int throws[MX];
int count[DICE]={0};
int n;
//printf("Number of dice to throw: ");
//scanf("%d",&n);
n=MX;
throwdice(throws,n);
//printf("Throw\tNumber");
//printv(throws,n);
countd(throws,n,count);
printf("\n\nNumber\tFrequency");
printv(count,DICE);
}
int genNum()
{
int n;
n=rand()%DICE+1;
return n;
}
void printv(int n[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("\n%d \t%d",i+1,n[i]);
}
void throwdice(int n[], int size)
{
int i;
for (i = 0; i < size; i++)
n[i]=genNum();
}
void countd(int n[], int size, int count[DICE])
{
int i;
for (i = 0; i < size; i++)
count[n[i]-1]++;
}
Is there a way to expand this program to account for, say a million throws?
Try changing this;
int throws[MX];
to either this, or move it to a global scope;
static int throws[MX];
I think you're probably overflowing the stack.
You can try to put the array on the heap like this;
int *throws = malloc(sizeof(int)*MX);

C: Printing out the value and memory location of each element of an array using pointers?

I have generated a random array inside the main function, How can I properly print it out using a separate function and inside the function print out the value and memory location of each element of that array using pointers. Here is my code so far:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void printArray(int *pointertoArray, int *Size);
int main (void)
{
srand(time(NULL));
int array[10];
int *pointer = NULL;
for(int i = 0; i < size; i++)
{
array[i] = rand();
*pointer = array[i];
printArray(*pointer,size);
}
}
void printArray(int *pointerToArray, int *size)
{
int i = 0;
do
{
printf("\nValue %d = %p ",i,*pointerToArray);
i++;
}
while(i < size);
}
Here is what I am trying to achieve:
value 1 = 0x7fff0815c0e0
.....
value 10 = 0x7fff0815c0ec
int *size should be int size. You don't pass a pointer, and you don't need a pointer.
Actually, size_t size would be more appropriate.
The call to printArray should be located after the loop. You only want to print the array once.
printArray(*pointer, size); should be printArray(array, size);.
pointerToArray should be named array or pointerToInts.
The value of the element is pointerToArray[i], not i.
The address of the element is pointerToArray+i, not *pointerToArray.
The loop in printArray should be top-tested. (No reason for it to be bottom tested, so play it safe.)
main is declared to return an int, but doesn't.
We get,
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void printArray(int *array, size_t size);
int main() {
srand(time(NULL));
int array[10];
for (int i = 0; i < size; ++i) {
array[i] = rand() % 1000;
}
printArray(array, sizeof(array)/sizeof(array[0]));
return 0;
}
void printArray(int *array, size_t size) {
for (int i = 0; i < size; ++i) {
printf("Value # %p = %d\n", array+i, array[i]);
}
}
Alternative:
void printArray(int *pointerToInt, size_t size) {
for (; size--; ++pointerToInt) {
printf("Value # %p = %d\n", pointerToInt, *pointerToInt);
}
}

Filling an array with a pointer to the array

#include <stdio.h>
#include <time.h>
#define SIZE 20
#define MIN 0
#define MAX 100
void FillArray(int *array, int size);
void PrintArray(int *array, int size);
void BubbleSort(int *array, int size);
void SelectionSort(int *array, int size);
void Swap(int *x, int *y);
int main() {
int NumList[SIZE];
int *array;
array = NumList;
FillArray(array, SIZE);
PrintArray(array, SIZE);
}
void FillArray(int *array, int size) {
int i;
srand(time(NULL));
for (i = 0; i < size; i++); //<--- the K&R brace style would make this bug obvious!
{
*(array+i) = MIN + rand() % (MAX - MIN + 1);
}
}
void PrintArray(int *array, int size) {
int i;
for (i = 0; i < size; i++) {
printf ("%d\n", array);
array++;
}
}
This program seems to be outputting random integers (not withing min and max) in increasing order, and I want to know why it's not random all the way through.
Specifically in the FillArray function. It seems to not be filling correctly.
You have no body to this loop
for (i=0; i<size; i++);
When it ends, the next line
*(array+i) = MIN + rand() % (MAX - MIN + 1);
writes outside the bounds of the array.
Remove that semicolon...
for (i=0; i<size; i++) // ---> ;
There is also the matter of
printf ("%d\n", array);
which should be
printf ("%d\n", *array);

Unable to shuffle cards randomly

I am doing a project that shuffle 10 cards (12) time randomly but it didn't work with my code.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void show(int[],int);
void shuffle(int[],int,int);
int main (void)
{
int karten[]={1,2,3,4,5,6,7,8,9,10};
int n = sizeof(karten)/sizeof(int);
//printf("%d",n);
int s=12;
srand(time(NULL));
printf("Karten vor dem Mischen: \n");
show(karten,n);
shuffle(karten,n,s);
printf("Karten nach dem Mischen:\n");
show(karten,n);
return 0;
}
void show(int karten[],int n)
{
for(int i=0;i<n;i++)
{
printf("%d,",karten[i]);
}
printf("\n");
}
void shuffle(int karten[],int n,int s)
{
int i=0;
int d=0;
int v[]={(int)malloc(sizeof(karten))};
for(int z=0;z<=s;z++)
{
i=rand()%10;
d=rand()%10;
//printf("%d-->%d\n",i,d);
v[i]=karten[i];
v[d]=karten[d];
karten[d]=v[i];
karten[i]=v[d];
}
printf("Es wurden %d Vertauschungen gemacht\n",s);
free(v);
}
The error is
(((process returned 255)))
and the program crashed.
void shuffle(int karten[],int n,int s) is equivalent to
void shuffle(int *karten,int n,int s)
so int v[]={(int)malloc(sizeof(karten))}; allocates just the size of karten
which is a pointer to an int, so 4 bytes(on most systems).
Because of that You are trying to access unallocated memory.
sizeof(karten) don't give you the length of the array, see sizeof array clarification. Just rewrite the code like this (don't need another array):
void shuffle(int karten[],int n,int s)
{
int i=0, vi;
int d=0, vd;
for(int z=0;z<=s;z++)
{
i=rand()%10;
d=rand()%10;
vi=karten[i];
vd=karten[d];
karten[d]=vi;
karten[i]=vd;
}
printf("Es wurden %d Vertauschungen gemacht\n",s);
}

Passing array to function using pointer

I'm trying to print array of pointer using pointer instead of array but I got this error Segmentation fault at runtime:
enter number of element:5
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
Segmentation fault
This is the code:
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int *array,int n);
void display(int *array,int n);
int sum(int *array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(array,n);
display(array,n);
result=sum(array,n);
printf("sum of array=%d",result);
return 0;
}
void input(int *array,int n){
int j;
array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",array+j);
}
}
void display(int *array,int n){
int j;
for(j=0;j<n;j++)
printf("%d\t",*(array+j));
printf("\n");
}
int sum(int *array,int n){
int sum=0,j;
for(j=0;j<n;j++)
sum+=*array+j;
return sum;
}
How can I fixed this code? please somebody explain me what's wrong with that code.
Variable array is a local variable in function input.
As such, it is pointless to set it with array = ..., because this assignment takes effect only inside the function. You should typically pass its address (&array) to any function that needs to change it.
In your specific example, you also have a global variable array, so a quick solution to your problem would be to simply call function input without passing variable array as an argument:
void input(int n)
{
...
array = (int*)malloc(n*sizeof(int));
...
}
int main()
{
...
input(n);
...
}
Note that this is a "dirty" workaround, and you should typically strive to avoid the use of global variables.
To add the clean version to barak's answer:
int input(int ** array, const size_t n)
{
int result = 0;
assert(NULL != array);
(*array) = malloc(n * sizeof(**array));
if (NULL == (*array))
{
result = -1;
}
else
{
size_t j;
for(j = 0; j < n; ++j)
{
printf("array[%zu]=", j);
scanf("%d", (*array) + j); /* still missing error checking here . */
}
}
return result;
}
And call it like this:
if (-1 == input(&array, n))
{
perror("input() failed");
exit(EXIT_FAILURE);
}
Try this input():
void input(int **array,int n){
int j;
*array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",*array+j);
}
}
Because C use pass-by-value, if you want to change the value of a variable in a function, you need to pass the address of that variable as the argument to that function.
In this case, you want to change the value of array in input() and the type of array is int *, therefore the prototype of input() should be something like void input (int **array, ...).
this should do..make sure you understand what the others have said..
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int **array,int n);
void display(int **array,int n);
int sum(int **array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(&array,n);
display(&array,n);
result = sum(&array,n);
printf("sum of array= %d",result);
return 0;
}
void input(int **array,int n){
int j;
*array= malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);
scanf("%d",(*array)+j);
}
}
void display(int **array,int n){
int j;
for(j=0;j<n;j++){
printf("%d\t",*((*array)+j)); // you can use array notation aswell
//array[0][j] will work
}
printf("\n");
}
int sum(int **array,int n){
int sum=0,j;
for(j=0;j<n;j++){
sum += *((*array)+j);
}
return sum;
}
What does *array + j do? Does it evaluate *array and add j to it? Or does it add j to array and then dereference it? Would you be willing to bet $100 on it if I told you you are wrong?
Make your life and the life of anybody reading your code easier by using parentheses, or even better, write array [j].

Resources