I am getting the Segmentation fault error on the Ubuntu machine but not on macOS.
Any help would be appreciated.
/**** main.c ****/
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <string.h> #define WORD_LEN 6 #define TOP 10 char * delim = "\"\'.“”‘’?:;-,—*($%)! \t\n\x0A\r"; struct Word { char word[30]; int freq; }; int threadCount; int fileDescriptor; int fileSize; off_t chunk; struct Word* wordArray; int arrIndex = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // initialize mutex lock /* add words to the struct array; mutex is used for protecting shared resources */ void addWord(char* token) { for (int i=0; i<=arrIndex; i++) { if (i == arrIndex) { pthread_mutex_lock(&lock); // mutex is locked here strcpy(wordArray[i].word, token); wordArray[i].freq++; arrIndex++; //wordArray = realloc(wordArray, sizeof((int*)wordArray)); // dynamically allocate memory for the array pthread_mutex_unlock(&lock); // mutex is unlocked here break; } else if (strcmp(wordArray[i].word, token) == 0) { // compare string in a case insensitive fashion pthread_mutex_lock(&lock); // mutex is locked here wordArray[i].freq++; pthread_mutex_unlock(&lock); // mutex is unlocked here break; } } } /* read words from each chunk of the file */ void* readWord(void* arg) { char* buf = (char*) malloc(chunk); // allocate memory for buffer /* use pread to read from a file descriptor at a given offset */ off_t* bufEnd = (off_t*) arg; off_t bufStart = *bufEnd - chunk; pread(fileDescriptor, buf, chunk, bufStart); /* splitting string by using strtok_r to maintain context between successive calls * that parse the same string */ char* token; while ((token = strtok_r(buf, delim, &buf))) { if (strlen(token) >= WORD_LEN) addWord(token); } pthread_exit(0); } void swap(struct Word* a, struct Word* b) { struct Word tmp = *a; *a = *b; *b = tmp; } int partition (struct Word arr[], int low, int high) { int pivot = arr[high].freq; // pivot int i = (low - 1); // index of smaller element for (int j = low; j <= high- 1; j++) { // if current element is smaller than the pivot if (arr[j].freq < pivot) { i++; // increment index of smaller element swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } void quickSort(struct Word arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); /* Separately sort elements before partition and after partition */ quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } int main (int argc, char *argv[]) { //***TO DO*** Look at arguments, open file, divide by threads // Allocate and Initialize and storage structures wordArray = malloc(1 * sizeof(struct Word)); // allocate memory for struct array if (!argv[1] || !argv[2]) { // make sure the user enter the file name and thread number printf("\nfile name or thread number is missing!\n\n"); exit(EXIT_FAILURE); } fileDescriptor = open(argv[1], O_RDONLY); // open the file for reading threadCount = atoi(argv[2]); // convert the thread number to an int fileSize = lseek(fileDescriptor, 0, SEEK_END); // get the file size chunk = (fileSize / threadCount); // divide the file by the number of threads /* get the position for each thread */ int* bufPosition[threadCount]; for (int i=0; i < threadCount; i++) bufPosition[i] = (int *) ((i + 1) * chunk); //************************************************************** // DO NOT CHANGE THIS BLOCK //Time stamp start struct timespec startTime; struct timespec endTime; clock_gettime(CLOCK_REALTIME, &startTime); //************************************************************** // *** TO DO *** start your thread processing // wait for the threads to finish pthread_t threadID[threadCount]; // array of threads /* create threads */ for (int i=0; i < threadCount; i++) pthread_create(&threadID[i], NULL, readWord, &bufPosition[i]); /* wait for each thread to terminate */ for (int i=0; i < threadCount; i++) pthread_join(threadID[i], NULL); // ***TO DO *** Process TOP 10 and display printf("\nWord Frequency Count on %s with %d threads\n", argv[1], atoi(argv[2])); printf("Printing top %d words %d characters or more.\n", TOP, WORD_LEN); /* sort the array in descending order and then print the top 10 */ quickSort(wordArray, 0, arrIndex); int n = 1; for (int j = arrIndex; j > arrIndex - TOP; j--) { printf("Number %d is %s with a count of %d\n", n, wordArray[j].word, wordArray[j].freq ); n++; } //************************************************************** // DO NOT CHANGE THIS BLOCK //Clock output clock_gettime(CLOCK_REALTIME, &endTime); time_t sec = endTime.tv_sec - startTime.tv_sec; long n_sec = endTime.tv_nsec - startTime.tv_nsec; if (endTime.tv_nsec < startTime.tv_nsec) { --sec; n_sec = n_sec + 1000000000L; } printf("Total Time was %ld.%09ld seconds\n", sec, n_sec); //************************************************************** // ***TO DO *** cleanup close(fileDescriptor); free(wordArray); }
Segmentation fault (core dumped) errors occur when you are trying to access a memory location that does not belong to you or you are trying to do something wrong with the memory. It occurs when you try to write into the read only memory.It also occurs when we try to access the freed or released memory location.It is reported several times during stack overflows and during the improper use of scanf.It can also be attributed to defrencing Null pointer.
Example 1 When a string is being modified
#include<stdio.h>
int main (void)
{
// writing to a read only memory initiate segmentation fault
char *s = "Virat Kohli is the greatest of all indian batsman" ;
*s= "H" ;
}
it will give segmentation error
Example 2 When scanf is used improperly
#include<stdio.h>
int main()
{
int p=10;
scanf("%d",p) ; //this is a bug!! we can't pass values here , it has to be an address
return 0;
}
It should be written as scanf("%d", &ch);
It will again on compilation will give segmentation error
Example 3 out of Array
#include<stdio.h>
int main()
{
int arr [10];
arr[11]=100; //this is illegal core dump!!
return 0;
}
Array has limit 0f 10 and we are assigning a value in 11 element so it will get error stack smash detector core dump
Example 4 Out of stack
In this we are showing recursion function
// this is recursion and it will cause stack overflow
#include<stdio.h>
int main (void)
{
main();
return 0;
}
main is inside int main , it is known as recursion it will keep on looping and looping and will cause segmentation.
There is nothing wrong with the program but due to excessive looping segmentation error occurs.
you can try these things out and eliminate any such instance from your program if it is encountered by you at any point of time.
I am getting the Segmentation fault error on the Ubuntu machine but not on macOS. Any...
#include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> #include <pthread.h> pthread_mutex_t mtx; // used by each of the three threads to prevent other threads from accessing global_sum during their additions int global_sum = 0; typedef struct{ char* word; char* filename; }MyStruct; void *count(void*str) { MyStruct *struc; struc = (MyStruct*)str; const char *myfile = struc->filename; FILE *f; int count=0, j; char buf[50], read[100]; // myfile[strlen(myfile)-1]='\0'; if(!(f=fopen(myfile,"rt"))){ printf("Wrong file name"); } else printf("File opened successfully\n"); for(j=0; fgets(read, 10, f)!=NULL; j++){ if (strcmp(read[j],struc->word)==0)...
In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...
I am having problems with the following assignment. It is done in the c language. The code is not reading the a.txt file. The instructions are in the picture below and so is my code. It should read the a.txt file and print. The red car hit the blue car and name how many times those words appeared. Can i please get some help. Thank you. MY CODE: #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char *str; int...
//In this assignment, we use multiple threads to calculate the frequencies of the first digits //of the numbers in an array of long integers #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> //#define NUM_THREADS 2 #define DIGITS 10 #define MAX 100000000 unsigned long a[MAX]; struct thread_data { int thread_num; int i, j; //the staring and ending index unsigned long freq[DIGITS]; // results }; //initialize the array void init_array(unsigned...
The following C code keeps returning a segmentation fault! Please debug so that it compiles. Also please explain why the seg fault is happening. Thank you #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // @Name loadMusicFile // @Brief Load the music database // 'size' is the size of the database. char** loadMusicFile(const char* fileName, int size){ FILE *myFile = fopen(fileName,"r"); // Allocate memory for each character-string pointer char** database = malloc(sizeof(char*)*size); unsigned int song=0; for(song =0; song < size;...
Write a cpp program Server.h #ifndef SERVER_H #define SERVER_H #include #include #include #include using namespace std; class Server { public: Server(); Server(string, int); ~Server(); string getPiece(int); private: string *ascii; mutex access; }; #endif -------------------------------------------------------------------------------------------------------------------------- Server.cpp #include "Server.h" #include #include Server::Server(){} Server::Server(string filename, int threads) { vector loaded; ascii = new string[threads]; ifstream in; string line; in.open(filename); if (!in.is_open()) { cout << "Could not open file...
How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses mutex to lock and unlock the shared resource (dotstr.sum) for access control as shown below. pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\n", offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); 2. Modify dot1m.c program to use reader-writer lock (instead of mutex). Replace the codes (for mutex) by the codes (for reader-writer lock). To initialize reader-writer lock, pthread_rwlock_initializer. At the end,...
Help with a Parallel and Distributed Programming assignment. In this assignment, you will be exploring different methods of counting the prime numbers between 1 and N. You will use 8 threads, and each will be given a range in which to count primes. The question is: where do you store your counter? Do you use a local variable? Do you use a global variable? Please use the following function to determine whether an integer number is a prime. // Return...
I am supposed to write documentation and report for the code below but I am new to operating system concepts I will appreciate if someone can help make a detailed comment on each line of code for better understanding. Thanks #include <pthread.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <ctype.h> #define handle_error_en(en, msg) \ do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) struct thread_info...
I am trying to figure out why my C code is outputting "exited, segmentation fault". The game is supposed to generate 4 random numbers and store them in the "secret" array. Then the user is suppose to guess the secret code. The program also calculates the score of the user's guess. For now, I printed out the random secret code that has been generated, but when the game continues, it will output "exited, segmentation fault". Also, the GetSecretCode function has...