Iqbal_h_a 0 Light Poster

Hi Guys,
I have a question on C++ object creation. Please consider the following code snippet.

class Foo {
private: int i;
public:  A(int ii):i(ii) {};
};
int main() {
 const Foo &ref = Foo(1);
}

Here I am bit confused about the line :
const Foo &ref = Foo(1);
Could anybody please explain me all behind the scene actions?
Why "const" key word is required here? How does this line is interpreted by compiler? We are not using "new" keyword here so I am bit confused how reference is returned?

Thank you.

Iqbal_h_a 0 Light Poster

Hi All,

I have resolved this issue. I have parsed the string till I get the whlole number.

Thank you very much jwenting and debasisdas for your valuable comments.

--Iqbal

Iqbal_h_a 0 Light Poster

You need to parse sysdate+1+2/24+20/(24*60) to proper format before processing in database.

Thank you very much Debasis for your valuable comments. I have tried to parse the string but at one point getting some error. Following is the parse code,

PROCEDURE JOB_EXPORT
IS
    cur CWTYPES.cursorType; 
    
    l_nextdate  DATE;         -- JOB_NEXT_RUN
    l_interval  VARCHAR2(64);
    v_string VARCHAR2(64);
    v_interval VARCHAR2(64);
    v_delimpos PLS_INTEGER;
    v_date DATE:=SYSDATE;
BEGIN
OPEN cur FOR
      SELECT JOB_NEXT_RUN, JOB_INTERVAL
FROM JOB_EXPORT_CDRS
      WHERE ACTIVE_STATUS=1
        AND JOB_INTERVAL IS NOT NULL
LOOP
      FETCH cur INTO l_nextdate,l_interval
EXIT WHEN cur%NOTFOUND;

if l_nextdate is NULL then
	l_nextdate:=SYSDATE;
	DBMS_OUTPUT.PUT_LINE(': nextdate is NULL, use SYSDATE as default');
else
       	v_interval := l_interval;
        v_delimpos := instr (v_interval, '+') + 1;
      	v_interval := SUBSTR(v_interval, v_delimpos);
      	v_delimpos := instr (v_interval, '+');
      	WHILE v_delimpos > 0
      	LOOP
      	   v_string := SUBSTR(v_interval, 1, v_delimpos-1);
      	   [B]v_date := v_date + v_string;[/B]
      	   v_interval := SUBSTR(v_interval, v_delimpos+1);
      	   v_delimpos := instr (v_interval, '+');
      	END LOOP;
          [B]v_date := v_date + v_interval;[/B]
end if;
commit;
END JOB_EXPORT;

I am getting the error at line v_date := v_date + v_interval;. Here I am adding parsed value(1 day) to sysdate at the first iteration of loop.
For ex if I am parsing the string sysdate+1+2/24+20/(24*60), on first iteration I am adding 1 to sysdate which is stored in v_date. But here 1 is stored in v_string(varchar2). So I am getting an error while executing the stored procedure. The error thrown is :
Database Error Message: ORA-06502: PL/SQL: numeric or value error: character to number conversion error

Can anyone please throw some light on …

Iqbal_h_a 0 Light Poster

Hi All,
I am struck with following problem. Please help me out.
I have defined a Oracle procedure as follows.

PROCEDURE JOB_EXPORT
IS
    cur CWTYPES.cursorType; 
    
    l_nextdate  DATE;         -- JOB_NEXT_RUN
    l_interval  VARCHAR2(64);
BEGIN
OPEN cur FOR
      SELECT JOB_NEXT_RUN, JOB_INTERVAL
FROM JOB_EXPORT_CDRS
      WHERE ACTIVE_STATUS=1
        AND JOB_INTERVAL IS NOT NULL
LOOP
      FETCH cur INTO l_nextdate,l_interval
EXIT WHEN cur%NOTFOUND;

if l_nextdate is NULL then
	l_nextdate:=SYSDATE;
	DBMS_OUTPUT.PUT_LINE(': nextdate is NULL, use SYSDATE as default');
else
        l_nextdate:=to_date('l_interval','dd-Mon-yyyy HH24:Mi:SS');
end if;
commit;
END JOB_EXPORT;

Here l_interval contains the value "sysdate+1+2/24+20/(24*60)". i.e. added 1 day, 2 hours and 20 minutes to the sysdate and put it in l_interval which is of varchar2. When I tried to assign this value to l_nextdate I am getting
the error
ORA-01858: a non-numeric character was found where a numeric was expected
The above error is getting thrown during run time and not during compile time.
Any help is greatly appreciated.
Thanks.

Iqbal_h_a 0 Light Poster

Hi All,

I have a doubt regarding "threadsafe". Consider the following scenario....

Thread #1:
          fun1() {
                  lock();
                  writestring(ptr, pconfig);
                  unlock();
                  }

     Thread #1:
          fun2() {
                   lock();
                   writestring(ptr, pconfig);
                   unlock();
                   }

          bool writestring(char *ptr, char *pconfig) {
              //this code should not be shared across threads. One thread should access at                                          
              //given point of time 
              memcpy();
              ............
              }

My doubt here is :

Will writestring is accessed by only one thread at any given point of time i.e. Is it Thread Safe? If no, then how can I make it threadsafe?

My application is multithreaded and crashing at memcpy i.e. memory corruption. Is thread safe is the reason for memory corruption? Please reply me.

Thanks in advance.

Iqbal_h_a 0 Light Poster

does your program ever call munmap() to release the memory back to the os? If not then maybe your program is just simply running out of memory.

Also about ftruncate() -- maybe you already know this.

Thank you very much for your kind reply. Sorry for late reply to your response to the query. I was not accessible to internet. The problem still persists. Looks like some other piece of code causing this problem.

Yes, I am calling munmap() and it is released properly. Suspecting strlen function causing the problem.

We are forming a string and it is not being null terminated. We are just concatenating "\n" to it and not "\0" and this string has been passed to strlen() function. Is this might be the cause for application crash?

Iqbal_h_a 0 Light Poster

Hi All,

I have built an application on C++. It is a multi threaded application. My application spawns 8 threads when it come up. Each thread opens one file and maps it using mmap.

It is a client-server application. Each thread picks up a message from the queue and processes it and finally using mmap stores it in a file.

Writing to the file and moving the file to another folder is fine. After running for 4 hours, application crashes (Segmentation Fault). When I debugged the core I came to know that SIGSEGV has been caught.

Here are some of the highlights of my codes snippets...

#define [B]NORMAL_CDRFILESIZE[/B] 1000000

if((m_hFile = fopen( m_currentFileName, "a+" ))==NULL)
    {
        cerr << "File could not be opened" << endl;
        return false;
    }

int fd = fileno(m_hFile);

if(ftruncate(fd,NORMAL_CDRFILESIZE) != 0)
    {
        perror("trucate error");
    }

mvmem =(char*) mmap(0, NORMAL_CDRFILESIZE, PROT_READ | PROT_WRITE,  MAP_SHARED, fd, 0); // mvmem is declared as char * mvmem

fmem = mvmem;

memcpy(fmem,pMsg,strlen(pMsg));  //pMsg is the buffer containing data to be written to the file

The above code snippet has been called by each thread in the application. I am using mutex lock and unlock when each thread executes the above code.

When I tried to debug the core file using dbx, it is at memcpy, the memory getting corrupted.

I have given a highlight of the code but actual code contains lots other computations.

Please let me know the cause for Segmentation Fault.

Thanks you very much in advance. …

Iqbal_h_a 0 Light Poster

I'd say that you're over interpreting the data.

Crash dumps have very little symbol information. It's probably just 6 words from the stack pointer. Whether that matches any parameters (or local variables) needs more research.

The only obvious bit of information is the fault address is memcpy + 0xe8

Thanks Salem for your kind reply.

Iqbal_h_a 0 Light Poster

I guess I should add:
stdc allows the use of memcpy with the arguments you stated. What the compiler calls as its own version of run-time memcpy can have any number of aguments. A lot of the API is a simplified wrapper to a much more messy-to-use system call.

Thanks Jim for your kind reply.

Iqbal_h_a 0 Light Poster

The following is the core dump got from the application crash(just took a line from the core dumped file).

003af9dc memcpy   (0, 0, 4629e8, 4629e8, 0, fbc06e65) + e8

I could not understand what it is trying to say here. As memcpy takes three parameters, here it is giving some 6 params. Can anybody explain me what these parameters stands for....

Thanks in advance.

Iqbal

Iqbal_h_a 0 Light Poster

Maybe Visual C++ allows objects of classes without data members to be declared const even when a constructor is not defined. Because there are no data members, there is no data to be initialized so there is nothing wrong with it. But VC gives a warning when objects of classes with data members are declared const without a proper constructor.

On the other hand g++ apparently doesnt give any room whether the class has data members or not.

I would quote the apporoprite portion of the C++ standard to find what it has to say about this, but I am a bit pressed for time.

Thanks a lot for your kind reply.

Iqbal_h_a 0 Light Poster

There is no such limitation. The above code compiles under Visual Studio 2003.

Thank you very much for your quick reply.
When I tried to compile under g++, it gave the above said error. Could you please clarify me with respect to g++. Thanks

Iqbal_h_a 0 Light Poster
#include<iostream>
using namespace std;
class test {
        public:
                void display() const {
                        cout<<"Hai Here in class"<<endl;
                        }
        };
int main() {
        const test b;
        b.display();
        }

When I execute the above code I got an error saying "uninitialized const b". But if I provide a default constructor it will compile without any error.
My question is, doesn't compiler provide the default constructor when we declare an object of type const? Any help is much appreciated.
Thanks in advance.

Iqbal_h_a 0 Light Poster

Hey buddy, the above code doesnt even compile since the size of the second variable (which is of type char) exceeds its limit since it has size 8 bits and u are trying to give it 24 bits.

And if you want to store something is char why not just assign it like normal variables.

Maybe you want something like:

typedef struct aaa {
    unsigned int  a : 4;
    unsigned char  b[24];
    unsigned int  c : 4;
}myStruct ;
 
int main (void)
{
    myStruct obj ;
    strncpy (obj.b, "abcdefghijklmnopqrstuvwxyz", 24) ;
    printf ("%s", obj.b) ;
 
    return 0 ;
}

Hope it helped, bye.

Thanks for your reply.
I am trying to pack in a single word but your structure is of 28 bytes size:-| .
As I mentioned in another reply, I am trying to use 4 bits for code, 24 bits for command(string type) and remaining 4 bits for error check(totally 32 bits == 4 bytes = word size in Linux).
Do you have any idea how this can be implemented(without exceeding 4 bytes)?

Iqbal_h_a 0 Light Poster

> My question is if it is allowed to declare char fields inside a structure
Yes, you can have chars in struct, you can even have char arrays in structs or pointers to chars.

You can even have a char bitfield, but only with fewer bits as already noted.

> we can not use functoins like strcpy
That's because you can't point at a bit-field member.

Why are you using bitfields anyway?

I am using this structure for protocol header which contains three fields(4 bits, 24 bits and 4 bits respectively)as I had indicated in the structure.
Anyway thanks for the reply.

Iqbal_h_a 0 Light Poster

When I compiled the follwing code snippet, it compiled without any error.
My question is if it is allowed to declare char fields inside a structure, then how can I store character string in that variable(we can not use functoins like strcpy:-| ).
OR
Is it not allowed to declare char inside?

#include <stdio.h>
#include <string.h>
int main() {
        struct aaa {
                unsigned int  a : 4;
                unsigned char  b : 24;
                unsigned int  c : 4;
                };
        struct aaa *pqr;
        }

Thanks

Iqbal_h_a 0 Light Poster

You can refer the following code if you would like to....

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
 
int main () {
        char host[] = "www.google.com";
        char delim[]=".";
        int i=0, index=0;
        char *token;
        char buf[100];
        char len_char;
        int length;
        token =  strtok(host, delim);
        buf[0]='\0';
        while (token != NULL) {
                length = strlen(token);
                sprintf(buf+strlen(buf), "%d", length);
                sprintf(buf+strlen(buf), "%s", token);
                token = strtok(NULL, delim);
                }
        printf("%d, %s\n", strlen(buf), buf);
        return 0;
        }
Iqbal_h_a 0 Light Poster

Compile your code in strict mode. I guess it should be error. Anyways return value in C on x86 is generally eax , where the result of the last calculation often happens to be placed. Maybe that's why you are seeing this result.

Cool explanation and I am cleared with all my doubts and even it has thrown an error when I compiled in strict mode as you expected.
Much appreciated reply:cool:

Iqbal_h_a 0 Light Poster

Your code probably shouldn't compile. add(int, int) is specified to return an int, but doesn't, which should raise a compile time error.

You are right. When I compiled in strict mode, it thrown a compilation error. But in normal mode it doesn't and it will act exactly as Grunt's explanation.
Anyway, thank you very much for your quick reply.

Iqbal_h_a 0 Light Poster

I have a doubt on function returning a value. Consider the following program snippet.

int add(int a,int b) {
   int c=a+b;
   return;
   }
 
 int main()  {
   int a=10,b=20;
   printf("%d %d %d",a,b,add(a,b));
   return(0);
   }

The above program gives the output as
10 20 30

But the function is not returning any value. According to the K&R C, Section 4.1,

".......there need be no expression after return; in that case, no value is returned to the caller."

I will be grateful if anyone explains the logic behind this cryptic.

Thanks in advance.

Iqbal_h_a 0 Light Poster

This page covers it a bit more thoroughly: http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1047673478&id=1043284351

Thank you dwks. It cleared my doubt.

Iqbal_h_a 0 Light Poster

Read this

Thanks Andor. Great reply.

Iqbal_h_a 0 Light Poster

To allocate two dimensional arrays

#include <stdlib.h>
#include <stdio.h>
int main()
{
   int ** array, i;
   array = calloc(256, sizeof(int));
   if (array == NULL)
   {
      printf("No mem!\n");
      return 1;
   }
   for (i=0; i<256; i++)
   {
      array[i] = calloc(256, sizeof(int));
      if (array[i] == NULL)
      {
         printf("No mem!\n");
         return 1;
      }
   }
 
   return 0;
}

Don't forgett to call free (same as you called calloc)

Andor, could you please tell me is not necessary to cast while allocating using calloc/malloc? If it does internally, is it same on all compilers?

Iqbal_h_a 0 Light Poster
cat /proc/meminfo

shows the current state of memory. The format varies somewhat with Linux distributions. My version of Linux has what you want in the 4 th column on the second line. So, you will need to get the awk statement working for you. Then put it in the C code.
You could also just read /proc/meminfo (read only) as a regular file and find the value using C only.
snippet:

#include <stdio.h>
void foo(void)
{
   char *cmd="awk '{ if(NR==2){print $4}}' /proc/meminfo";
   FILE *cmdfile=popen(cmd,"r");
   char result[256]={0x0};
   while(fgets(result,sizeof(result),cmdfile)!=NULL) 
   {
       printf("%s\n",result);
   }
   pclose(cmdfile);
}

Thank you very much Jim. It is really a great help.:)

Iqbal_h_a 0 Light Poster

Please post your question outside code tags. I corrected your first two posts, do this one yourself, or I will delete this thread. Since it has been only 2 minutes since your post, you can edit it now.

Sorry for my ignorance. As I am new to this blog, I was unaware of the rules.
I tried to edit the post as you suggested, but could not do so.
I will definitely take care of all the rules in my future posts.
I am extremely sorry if I hurt anybody by breaking the rules.
Thanks
Iqbal

Iqbal_h_a 0 Light Poster

It will be helpful if somebody explains how to calculate total free memory in linux OS.
Thanks

Iqbal_h_a 0 Light Poster
Can anybody please tell me how to calculate/find total remaining(unused/free) memory in the system(using any functions)?
 
Thanks
Iqbal
WolfPack commented: Code Tags not used properly. +0
Iqbal_h_a 0 Light Poster
Please look at the following code snippets:
 
char str[]="abcd"; // Gets stored in stack frame.
 
char *str="abcd"; // Where does this gets stored?
 
 
In case of first declaration ie char str[]="abcd"; the string "abcd" gets stored in the stack frame of the invoked funciton. I wonder where does the string gets stored when we declare char *str="abcd"; (Is it in the heap?). Please reply.
 
 
Thanks
Iqbal
WolfPack commented: Improper use of Code Tags +0
Iqbal_h_a 0 Light Poster

Thank you very much for the kind reply.

Iqbal_h_a 0 Light Poster

It is not allowed to declare a variable of same structure type but it is allowed to declare a pointer. For example,

struct node {
     int a;
     struct node x;    //not allowed
     struct node *pnext;   //allowed
     };

My question is when we can declare a pointer of same type why not a variable of same type.
I will be exremely grateful if somebody answers my question.

Thanks
Iqbal