PSET 5 "SPELLER" : Complies correctyly but during running this hash function resulting in SEGMENTATION FAULT(core dump)? - cs50

If I run it in another smaller program it works fine( returns the key correct) but on the pset 5 speller it gives segmentation fault. Why?
enter image description here
//HASHES WORD TO A NUMBER
unsigned int hashing(int power, const char*word);
unsigned int hash(const char *word)
{
unsigned int key = hashing(2,word);
return key;
}
unsigned int hashing(int power, const char*word)
{
if(power==0)
{
return (*word-'a');
}
return ( (pow(26,power) * (*word-'a')) + (hashing(power-1,word+1)) );
}

Related

Line 1034: Char 9: runtime error: reference binding to misaligned address 0xbebebebebebebebe for type 'int', which requires 4 byte alignment

I'm getting runtime error for this problem 01 Matrix (https://leetcode.com/problems/01-matrix/description/ Can anyone check what's wrong with my code/logic?
My code:-
class Solution {
public:
int f(int i,int j,vector<vector<int>>& mat,vector<vector<int>>&dp){
if(i<0 or i>mat.size())return -1;
if(j<0 or j>mat[0].size())return -1;
if(mat[i][j]==0){
return 0;
}
if(dp[i][j]!=-1) return dp[i][j];
int l=f(i,j-1,mat,dp);
int r=f(i,j+1,mat,dp);
int u=f(i-1,j,mat,dp);
int d=f(i+1,j,mat,dp);
return dp[i][j]=1+min({l,d,r,u});
}
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int n=mat.size();
int m=mat[0].size();
vector<vector<int>> v(n+1,vector<int>(m+1,0));
vector<vector<int>> dp(n+1,vector<int>(m+1,-1));
for(int i=0;i<mat.size();i++){
for(int j=0;j<mat[0].size();i++){
v[i][j]=f(i,j,mat,dp);
}
}
return v;
}
};
I tried running the code and I was getting an error(as pasted above) Can someone help me?

message queue: call msgsnd return -1

It has been confusing me for two days, I use msgsnd to send a message but return -1, while the error number errno is 22(EINVAL) which means "Invalid argument". In the document, it shows this error will occur if the following condition meet:
Invalid msqid value, or nonpositive mtype value, or invalid msgsz value (less than 0 or greater than the system value MSGMAX).
In my code, msqid is 0 which is correct, while mtype is 16 and msgsz is 1600. The value MSGMAX in /proc/sys/kernel/msgmax is 8192 which is default and bigger than 1600. So I think all these conditions are fulfilled. But I suspect that it's msgsz problem because when I reducing the size 1600 to 1000, this message can be sent.
Here comes my code:
typedef struct
{
MASK_BASE_UNIT value[MASK_SIZE(MAX_PORTS)];
} PORT_MASK_t;
typedef struct _packet_
{
unsigned char data[MAX_PACKET_SIZE]; //MAX_PACKET_SIZE = 1558
unsigned int asic;
unsigned int pkt_len;
unsigned int source_port;
PORT_MASK_t dst_port_mask;
} PACKET_t;
typedef struct _packet_msg_
{
unsigned int appMask;
PACKET_t packet;
int ltcRequestId;
} MSG_t;
STATUS pkt_mux_packet_handler (MSG_t *msg)
{
MSG_t msg_data;
...
memset(&msg_data, 0, sizeof(msg_data));
memcpy(&msg_data, msg, sizeof (msg_data));
if (-1 == msgsnd (pkt_mux_info.recvMsgQid, &msg_data, sizeof(MSG_t), 0)) //sizeof(MSG_t) == 1600
{
printf("%s called, failed: errno: %s, error code:%d\n", __func__, strerror(errno), errno);
fflush(stdout);
return STATUS_FAILURE;
}
}
There is another strange thing that if I clear the data array in the msg_data->packet, this message can be sent successfully.

Incorrect interprocess reading

I'm doing a client/server communication system with shared memory. I'm writing with the client the PID which the Server will then read. The problem is that when I try to read the value, it only reads the least signficant 8 bits. Here's a chunk of the code:
int receive(void* data, void * connection) {
connection_t * c = (connection_t *)connection;
printf("PRINTING: %d \n", *(c->address));
return 0;
}
void notify_server() {
int mem_id = shmget(PUBLIC_KEY, PAGE_SIZE, PERMISSION_FLAGS);
int * address = shmat(mem_id, NULL, 0);
int sem_id = semget(PUBLIC_KEY, 1, PERMISSION_FLAGS);
*address = (pid_t)PRIVATE_KEY;
printf("FROM CLIENT, PRINT MY PID --- %d\n", *address);
}
The structure is:
typedef struct {
int id;
char * address;
struct shmid_ds data;
int sem_id;
struct sembuf sb;
} connection_t;
The address field is a char: char * address;
So of course *(c->address) will give a char which is 8 bits.

Initial assignment a Char Array using a Function in C

as we know it in C, a string defining is,
char string[] = "Hello World";
That is OK,
But I want to use a function and at initial same up,
I tried those, For example;
char * to_string()
{
return "Hello World";
}
Or;
char * to_String(void) // Function
{
char buff[16];
sprintf(buff, "%s", "Hello World");
return buff;
}
main() // main function
{
char Initial_String[] = to_String();
}
How to make this or any idea same another way.
I find what I dont send address of char Initial_String[] to fill into. No. is there Another method.
Thanks.
When you compile this, atleast in GCC, it will give you the following warning:
b.c:9: warning: function returns address of local variable
Why? Because buff[] is a local variable of function to_string(). Its scope is only inside the function to_string(). main() does not have any access to this variable. Try making buff[] a global variable instead.
Second problem: char Initial_String[] = to_String(); cannot be assigned value in this way. to_string() returns a char pointer, hence assign the value thus:
char *Initial_String = to_String();
The code below will work:
char buff[16];
char* to_String(void) // Function
{
//char buff[16]; /*this is a local variable*/
sprintf(buff, "%s", "Hello World");
return buff;
}
int main(void) // main function
{
char *Initial_String = to_String();
printf("%s", Initial_String);
return 0;
}
Yes You are right about local buffer mismake,
But This is not my wanting,
if I edit some differently,
char buff[16];
char* to_String(void) // Function
{
//char buff[16]; /*this is a local variable*/
sprintf(buff, "%s", "Hello World");
return buff;
}
int main(void) // main function
{
char *Initial_String_1 = to_String();
char *Initial_String_2 = to_String();
char *Initial_String_3 = to_String();
printf("%s", Initial_String_1 );
printf("%s", Initial_String_2 );
printf("%s", Initial_String_3 );
in this case, all strings will be same, because They have same buffer address,
I want to open the topic little more.
struct
{
long aaa;
short bbb;
int ccc;
char ddd;
.
.
. // the list goes on
}elements;
typedef struct
{
int lengt;
int *adress;
char name[10];
}_list;
char* to_String(long variable) // Function
{
sprintf(buff, "%ld", variable);
return buff;
}
int main (void)
{
_list My_List[] = {
{ sizeof(elements.aaa), &elements.aaa , to_string( elements.aaa) },
{ sizeof(elements.bbb), &elements.bbb , to_string( elements.bbb) },
{ sizeof(elements.ccc), &elements.ccc , to_string( elements.ddd) },
.
.
. //// the list goes on
};
I do not know, Do I make myself clear.
Here, string must be filled into name array, without assigning it the address.
I may have syntax mistake. the code is not tested with compiler. the idea is for illustrative purposes only.
I am trying to find a method for The purpose.
Thanks.

Error handling failure

I'm new and a novice programmer and trying to learn.. I've been trying to do a library program using structures, with the following functions I've created. add a new customer, find number of customers, print details of a customer,borrow book,reserve book, return book
what I failed is that ; when I add a new customer my program asks for name, address and Id, and, and I want my program to give an error message when I try to register a new customer with an already existing id, I'm also going to post my codes.
I'm not asking for codes from you, I just want to know, what I've done wrong and how I can fix it, any hints will be appreciated thanks
My Codes:
#include <iostream>
using namespace std;
const int maxx=100; //max 100 users
const int maxborrow=5; //maxx borrow books
int bi=0; //counter for books
int i=0; //counter for users
int number_of_customers=0;
//initialize numebr of users to 0
struct loanreserved
{
int loan; // 1 indicates true 0 indicates false if a book is reserved for example it's 1 if available 0
int reserved;
};
struct duedate
{
int day;
int month;
int year;
};
struct bookinf
{
char title[maxx];
char author[maxx];
int ISBN;
loanreserved loanorreserved;
duedate bookduedate;
};
struct userinf
{
char name[maxx];
char address[maxx];
int Id;
int number_of_reserved_books;
int number_of_loan_books;
bookinf customersbookinf[maxborrow];
};
userinf uniclibrary[maxx];
int readcustomer()
{
int uniqueid;
cout<<"Customer name: ";
cin>>uniclibrary[i].name;
cout<<"Customer address: ";
cin>>uniclibrary[i].address;
cout<<"Customer Id: ";
cin>>uniqueid; //save id to temp file;
for(int x=0;x<maxx;x++)
{
if(uniqueid!=uniclibrary[x].Id)
{
uniclibrary[i].Id=uniqueid;
cout<<"Customer registration succeeded ! \n";
number_of_customers++;
return 1; //success
}
}
cout<<"This user is already registered ! ";
return 0; //fail
system("pause");
system("cls");
You can have a static variable that keeps track of existing customers:
#include <set>
int readcustomer()
{
static std::set<std::string> existingNames;
std::string name;
cout<<"Customer name: ";
cin>>name;
if ( existingNames.find(name) != existingNames.end() )
{
//name already exists
return 0;
}
else
{
existingNames.insert(name);
}
//....
}
Of course, this is a quick fix. Better take your code to codereview. The're MUCH that can be improved.

Resources