Sponsored Content
Top Forums Programming Segmentation Fault ERROR in C Post 302958164 by Don Cragun on Tuesday 20th of October 2015 05:39:27 AM
Old 10-20-2015
Quote:
By inc the i an j, I'm giving the dimension of the array until it reaches its max which is N^2 or am I incorrect?
No! You are creating an array of N^2 pointers to pointers to ints. So you have to store pointers to ints in the elements of the 1st dimension of the array (but you were storing ints there; not pointers to ints). And since (in a 64-bit programming environment) ints and pointers to ints are not the same size, storing an int in an area reserved for a pointer to an int might or might not work, but referencing the items stored in rows in the array as ints in check_property() will not reference the spots in which you stored them with your scanf() calls where you stored them in an object of type pointer to pointer to int. But you die before you get there because dereferencing vec[0][0] in scanf("%d", &vec[i][j]) uses vec[0] as a pointer, but you haven't initialized vec[0] yet, so you get a memory fault. And, if that location was a random value that points to a valid address, after you store an int there with your first scanf() call, dereferencing &vec[0][1] on the next call to scanf() will use the integer that you scanned on the first call as a pointer (but you stored an int there). The likelihood that the integer read in the 1st scanf() is a valid pointer is fairly low, and if it does happen to be valid, the likelihood that the integer value you stored in vet[0][0] is actually the address in memory of vec[0][0] is EXTREMELY unlikely. And it gets worse and worse as you scan more integers into the pointers to integers allocated for vec[].

So, if you want to use a doubly dimensioned array the following code tries to do what I think you were trying to do. Here are a few notes concerning the following code:
  1. If you want to use a doubly dimensioned array, you have to create a doubly dimensioned array. In other words, vec in your code needs to be allocated as an array of N pointers to arrays of integers and each element of vec[] needs to be allocated as a pointer to an array of N integers.
  2. I made several stylistic changes to fit my programming style.
  3. I replaced the min() function with a macro.
  4. I renamed the check() function PowerOf2() (and modified it to allow all non-negative integral powers of 2; not just positive integral powers of 2).
  5. I added lots of debugging statements (trying to make sense of your comments about the check_property() function).
Code:
#include <stdio.h>
#include <stdlib.h>

#define min(a, b)	(a < b ? a : b)

int check_property(int *row, int iL, int iR) {
	int	k, res, resl, resr;
	int	iM = (iR - iL) / 2;

	printf("check_property(%p, %d, %d) row[%d]=%d, row[%d]=%d\n",
	    row, iL, iR, iL, row[iL], iR, row[iR]);
	if (iM == 0) {
		printf("check_property(%p, %d, %d) returning %d\n",
		    row, iL, iR, row[iL] == row[iR]);
		return(row[iL] == row[iR]);
	}
	for (res = 1, k = 0; k < (iR-iL); k++) {
		if (row[iL + k] != row[iL + k + 1]) {
			res = 0;
			break;
		}
	}
	resl = check_property(row, iL, iL + iM);
	resr = check_property(row, iL + iM+1, iR);
	printf("check_property(%p, %d, %d) returning %d\n",
	    row, iL, iR, res + min(resl,resr));
	return(res+min(resl,resr));
}

/* Return 1 if N is a power of 2; otherwise, 0. */
/* Note that 1 is 2**0 and is a power of 2. */
int PowerOf2(int N) {
	int K = 1;
	while (K < N)
		/* Shift left one bit and multiply by 2 produce the same
		** results.
		*/
		K <<= 1;
	return(K == N);
}

int main(int argc, char *argv[]) {
	int	i,
		j,
		N,
		result = 0,
		**vec;

	if(argc < 2) {
		fprintf(stderr, "Usage: %s N\n", argv[0]);
		exit(1);
	}

	/* ... how many numbers to read */
	N = atoi(argv[1]);
	/* check if N is a power of two; exit if not */
	if(! PowerOf2(N)) {
		fprintf(stderr,
		    "%d is not a power of 2 as required.  Exiting.\n", N);
		exit(2);
	}

	/* Create array of N pointers to arrays of ints. */
	vet = (int**)malloc(N * sizeof(int*));
	if(vec == NULL) {
		fprintf (stderr, "ERROR: not enough memory available!\n");
		exit(3);
	}
	/* Now create N arrays of N ints. */
	for(i = 0; i < N; i++) {
		/* Note sizeof(int); not int* in following malloc(). */
		vec[i] = (int*)malloc(N * sizeof(int));
		if(vec[i] == NULL) {
			fprintf(stderr,
			    "ERROR: not enough memory available!\n");
			exit(3);
		}
	}

	for(i = 0; i < N; i++)
		for(j = 0; j < N; j++)
			scanf("%d", &vec[i][j]);

	printf("\nOriginal array:\n");  /* Trailing space removed from format.*/
	for(i = 0; i < N; i++) {
		for(j = 0; j < N; j++)
			printf("%d ", vec[i][j]);
		printf("\n");
	}

	/* Now process array; example below is to add numbers */
	/* Saying that check_property() adds numbers is not at all enlightening.
	** It seems to return 1 if all pairs of numbers on a row have the same
	** value (or if there is only one element on a row) and to return 0 if
	** one or more pairs of numbers on a row have different values.
	*/
	for(i = 0; i < N; i++) {
		printf("Processing row %d...\n", i);
		result = check_property(vec[i], 0, N-1);
		printf("result[row %d]: %d\n", i, result);
	}

	/* free memory */
	for(i = 0; i < N; i++)
		free(vec[i]);
	free(vec);

	exit(0);
}

This User Gave Thanks to Don Cragun For This Post:
 

10 More Discussions You Might Find Interesting

1. Programming

Hi! segmentation fault

I have written a program which takes a directory as command line arguments and displays all the dir and files in it. I don't know why I have a problem with the /etc directory.It displays all the directories and files untill it reaches a sub directory called peers which is in /etc/ppp/peers.the... (4 Replies)
Discussion started by: vijlak
4 Replies

2. AIX

Segmentation fault

Hi , During execution a backup binary i get following error "Program error 11 (Segmentation fault), saving core file in '/usr/datatools" Riyaz (2 Replies)
Discussion started by: rshaikh
2 Replies

3. UNIX for Dummies Questions & Answers

What's the difference between Segmentation fault and Bus error and Illegal...?

What's the difference between Segmentation fault and Bus error and Illegal instruction? Sometimes I got the one, and sometimes i got another, what are their differences? Segmentation fault (core dump)? Bus error (core dump)? Illegal instruction (core dump) Thanks Daniel (2 Replies)
Discussion started by: lakeat
2 Replies

4. UNIX for Advanced & Expert Users

capture sqsh segmentation fault error

hi all is there any way to capture the segmentation fault error when i run sqsh on a unix shell script. Ex: #!/bin/ksh sqsh -S "server" -U "user" -P "pwd" << EOF use mydb go exec proc1 go exit EOF retval=$? echo "sqsh return value $retval" if then exit (1 Reply)
Discussion started by: sudheer1984
1 Replies

5. Programming

segmentation fault

Hi, I am having this segmentation fault not in the following program, bt. in my lab program . My lab program is horrible long so cannot post it here bt. I am using the following logic in my program which is giving the segmentation fault. Bt. if I run this sample program as it is it dosen't give... (3 Replies)
Discussion started by: mind@work
3 Replies

6. Shell Programming and Scripting

Segmentation Fault(Core Dump) Error

Hi all, I have a folder with some 28 files. I have a script file that will iteratively take one file at a time from the folder and provide an output for the input file. Till the 7th file, there was no problem but from the 8th file onwards, i got this Segmentation Fault(Core Dump) error. A file... (2 Replies)
Discussion started by: mick_000
2 Replies

7. Programming

getting Segmentation Fault (core dumped) error but Program runs fine.

i am executing following program int main() { char str; FILE * fp; int i=0; ... (4 Replies)
Discussion started by: bhavesh.sapra
4 Replies

8. Programming

segmentation fault.

This code is causing a segmentation fault and I can't figure out why. I'm new to UNIX and I need to learn how to avoid this segmentation fault thing. Thank you so much. Thanks also for the great answers to my last post.:):b: int main() { mysqlpp::Connection conn(false); if... (3 Replies)
Discussion started by: sepoto
3 Replies

9. Programming

Using gdb, ignore beginning segmentation fault until reproduce environment segmentation fault

I use a binary name (ie polo) it gets some parameter , so for debugging normally i do this : i wrote script for watchdog my app (polo) and check every second if it's not running then start it , the problem is , if my app , remain in state of segmentation fault for a while (ie 15 ... (6 Replies)
Discussion started by: pooyair
6 Replies

10. Programming

C. To segmentation fault or not to segmentation fault, that is the question.

Oddities with gcc, 2.95.3 for the AMIGA and 4.2.1 for MY current OSX 10.14.1... I am creating a basic calculator for the AMIGA ADE *NIX emulator in C as it does not have one. Below are two very condensed snippets of which I have added the results inside the each code section. IMPORTANT!... (11 Replies)
Discussion started by: wisecracker
11 Replies
All times are GMT -4. The time now is 04:12 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy