Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New to C programming on linux, stuck at typecasting

I am pretty new to programming on Linux. I am trying to implement a message queue in one of my assignments. But I am not able to do it. The code is as follows :

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <linux/sched.h>
#include <stdlib.h>
#include <string.h>

typedef long MSISDN;
typedef struct 
{
   long mtype;
   long mtext;
}msgbuf;

void init(int qid,int key) {
   qid = msgget(key,IPC_CREAT|0666);
}

void sendMsg(long t_ype, long buf, int len, int qid) {

   int length = sizeof(long) + sizeof(MSISDN);
   msgbuf *p = malloc(length);
   p->mtype = t_ype;
   fputc('2',stderr);
   void* tosend = (void*) buff;
   fputc('3',stderr);

   memcpy(p->mtext,tosend,length);

   fputc('4',stderr);
   msgsnd(qid,p,length,IPC_NOWAIT);
   free(p);
}



void main()
{
   int qid;
   int key = 1111;
   int len= sizeof(MSISDN); 
   long type_1=1;
   long send = 12345;

   init(qid,key);
   fputc('1',stderr);
   sendMsg(type_1,send,len,qid);

   getchar();
}

The problem is memcpy is not working . I am getting a warning :

. warning: passing argument 1 of ‘memcpy’ makes pointer from integer without a cast [enabled by default]

Also when I run the code it gets a SIGSEGV signal at the memcpy. I think I am not getting the typecast correctly.

like image 804
anshu Avatar asked Feb 15 '12 17:02

anshu


2 Answers

It's not the typecast, it's the argument itself. p->mtext is a long, not a pointer. You need to send the address of p->mtext as the dest argument to memcpy. You're getting the segfault because memcpy is trying to write to the memory address pointed to by p->mtext, which is clearly not in your process' address space.

That's the reason - since this is a homework assignment, I'll leave the fixing of the code up to you.

like image 140
Harper Shelby Avatar answered Sep 24 '22 01:09

Harper Shelby


You would explicitly type cast a variable like this

 double num = 1.11;
 int num2 = (int)num;

num = 1.11 num2 = 1

like image 42
Mitchell Ciupak Avatar answered Sep 21 '22 01:09

Mitchell Ciupak