Thursday, 15 August 2013

Tricky C questions

Tricky C questions
By admin | May 10, 2006

    How do you write a program which produces its own source code as its output?
    How can I find the day of the week given the date?
    Why doesn’t C have nested functions?
    What is the most efficient way to count the number of bits which are set in a value?
    How can I convert integers to binary or hexadecimal?
    How can I call a function, given its name as a string?
    How do I access command-line arguments?
    How can I return multiple values from a function?
    How can I invoke another program from within a C program?
    How can I access memory located at a certain address?
    How can I allocate arrays or structures bigger than 64K?
    How can I find out how much memory is available?
    How can I read a directory in a C program?
    How can I increase the allowable number of simultaneously open files?
    What’s wrong with the call fopen(”c:\newdir\file.dat”, “r”)?

what are storage-class specifier , auto/extern/static
How can you swap two integer variables without using a temporary?
1.12: What is sizeof('A') ?



A: The same as sizeof(int).  Character constants have type

 int in C.  (This is one area in which C++ differs.)

what is the return type of malloc.... it is void*
we need to typecast it to appropriate object.

char *p = malloc(n * sizeof(char));


How would you implement the va_arg() macro in

 <stdarg.h>?


1.24: State the declaration for a pointer to a function

 returning a pointer to char.



A: char *(*f)();

1.23: What do these declarations mean?



     int **a();

     int (*b)();

     int (*c[3])();

     int (*d)[10];



A: declare a as function returning pointer to pointer to int

 declare b as pointer to function returning int

 declare c as array of 3 pointers to functions returning int

 declare d as pointer to array of 10 ints



 The way to read these is "inside out," remembering that

 [] and () bind more tightly than *, unless overridden by

 explicit parentheses.


1.28: Consider these definitions:



     #define Push(val) (*stackp++ = (val))

     #define Pop() (*--stackp)



     int stack[100];

     int *stackp = stack;



 Now consider the expression



     Push(Pop() + Pop())



 1. What is the expression trying to do?  In what sort of

 program might such an expression be found?



 2. What are some deficiencies of this implementation?

 Under what circumstances might it fail?



A: The expression is apparently intended to pop two values

 from a stack, add them, and push the result.  This code

 might be found in a calculator program, or in the

 evaluation loop of the engine for a stack-based language.



 The implementation has at least four problems, however.

 The Push macro does not check for stack overflow; if more

 than 100 values are pushed, the results will be

 unpredictable.  Similarly, the the Pop macro does not

 check for stack underflow; an attempt to pop a value when

 the stack is empty will likewise result in undefined

 behavior.



 On a stylistic note, the stackp variable is global as far

 as the Push and Pop macros are concerned.  If it is

 certain that, in a particular program, only one stack

 will be used, this assumption may be a reasonable one,

 as it allows considerably more succinct invocations.

 If multiple stacks are a possibility, however, it might

 be preferable to pass the stack pointer as an argument

 to the Push and Pop macros.



 Finally, the most serious problem is that the "add"

 operation as shown above is *not* guaranteed to work!

 After macro expansion, it becomes



     (*stackp++ = ((*--stackp) + (*--stackp)))



 This expression modifies a single object more than once

 between sequence points; specifically, it modifies stackp

 three times.  It is not guaranteed to work; moreover,

 there are popular compilers (one is gcc) under which it

 *will* *not* work as expected.  (The extra parentheses

 do nothing to affect the evaluation order; in particular,

 they do not make it any more defined.)


how does printf works. what is the output of printf{"%d"'}


char *x = "abc";
char arr[] = {a,b,c};

sizeof(x) and sizeof(arr)

1.52: How can a header file be protected against being

 included multiple times (perhaps due to nested

 #include directives)?



A: The standard trick is to place lines like



     #ifndef headerfilename_H

     #define headerfilename_H



 at the beginning of the file, and an extra #endif at the

 end.


what is difference in header file and library
what is the return type of sizeof ... unsigned int or unsigned long int
what is memory leak...
malloc realloc... offset pointers


#define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}

Answer:
64

Explanation:
the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64


Predict the output or error(s) for the following:

main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}

Answer:
1

Explanation:
Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1.

Configuring Disks for ASM

Configuring Disks for ASM

To configure disks for use with ASM on AIX, follow these steps:

    If necessary, install the shared disks that you intend to use for the ASM disk group and restart the system.

    To make sure that the disks are available, enter the following command on every node:

    # /usr/sbin/lsdev -Cc disk


    The output from this command is similar to the following:

    hdisk0 Available 1A-09-00-8,0  16 Bit LVD SCSI Disk Drive
    hdisk1 Available 1A-09-00-9,0  16 Bit LVD SCSI Disk Drive
    hdisk2 Available 17-08-L       SSA Logical Disk Drive


    If a disk is not listed as available on any node, enter the following command to configure the new disks:

    # /usr/sbin/cfgmgr


    Enter the following command on any node to identify the device names for the physical disks that you want to use:

    # /usr/sbin/lspv | grep -i none


    This command displays information similar to the following for each disk that is not configured in a volume group:

    hdisk2     0000078752249812   None


    In this example, hdisk2 is the device name of the disk and 0000078752249812 is the physical volume ID (PVID). The disks that you want to use might have a PVID, but they must not belong to a volume group.

    If a disk that you want to use for the disk group does not have a PVID, enter a command similar to the following to assign one to it:

    # /usr/sbin/chdev -l hdiskn -a pv=yes


    On each of the other nodes, enter a command similar to the following to identify the device name associated with each PVID on that node:

    # /usr/sbin/lspv | grep -i 0000078752249812


    Depending on how each node is configured, the device names might differ between nodes.

    To enable simultaneous access to a disk device from multiple nodes, you must set the appropriate Object Data Manager (ODM) attribute listed in the following table to the value shown, depending on the disk type:
    Disk Type     Attribute     Value
    SSA or FAStT disks     reserve_lock     no
    ESS, EMC, HDS, CLARiiON, or MPIO-capable disks     reserve_policy     no_reserve

    To determine whether the attribute has the correct value, enter a command similar to the following on all cluster nodes for each disk device that you want to use:

    # /usr/sbin/lsattr -E -l hdiskn

    If the required attribute is not set to the correct value on any node, enter a command similar to one of the following on that node:

        SSA and FAStT devices:

        # /usr/sbin/chdev -l hdiskn  -a reserve_lock=no


        ESS, EMC, HDS, CLARiiON, and MPIO-capable devices:

        # /usr/sbin/chdev -l hdiskn  -a reserve_policy=no_reserve


    Enter commands similar to the following on any node to clear the PVID from each disk device that you want to use:

    # /usr/sbin/chdev -l hdiskn -a pv=clear


    Enter commands similar to the following on every node to change the owner, group, and permissions on the character raw device file for each disk that you want to add to the disk group:

    # chown oracle:dba /dev/rhdiskn
    # chmod 660 /dev/rhdiskn


    Note:
    If you are using a multi-pathing disk driver with ASM, make sure that you set the permissions only on the correct logical device name for the disk.

    The device name associated with a disk might be different on other nodes. Make sure that you specify the correct device name on each node.

    If you also want to use raw devices for storage, refer to the "Configure Raw Devices" section.

    Otherwise, refer to the "Verify the Cluster Software Configuration" section.

ORA-12012: error on auto execute of job "ORACLE_OCM"."MGMT_CONFIG_JOB_2_1" ORA-29280: invalid directory path ORA-06512: at "ORACLE_OCM.MGMT_DB_LL_METRICS", line 2436 ORA-06512: at line 1

Errors in file $ORA_BASE/diag/rdbms/oastdb/oastdb1/trace/oastdb1_j001_22085770.trc:
ORA-12012: error on auto execute of job "ORACLE_OCM"."MGMT_CONFIG_JOB_2_1"
ORA-29280: invalid directory path
ORA-06512: at "ORACLE_OCM.MGMT_DB_LL_METRICS", line 2436
ORA-06512: at line 1
Tue May 22 22:15:12 2012


Following errors in the alert.log file:

ORA-12012: error on auto execute of job “ORACLE_OCM”.”MGMT_CONFIG_JOB_2_1?
ORA-29280: invalid directory path

This messages happen because of the OCM collection database job is unable to access the directory location where the OCM data is written .

you do not use OCM delete the OCM configuration from the database:

Log in to your database as user SYS and drop-cascade user ORACLE_OCM:
SQL> DROP USER ORACLE_OCM CASCADE;

If you using OCM to upload collection to My Oracle Support  please refer to note [ID 1378564.1 to re instrument your database


Ora-12012: Error On Auto Execute Of Job "Oracle_ocm"."Mgmt_config_job_2_1" [ID 1378564.1]
      Modified 13-DEC-2011     Type PROBLEM     Status PUBLISHED    

In this Document
  Symptoms
  Cause
  Solution

Applies to:
Oracle Configuration Manager - Version: 10.0.0 and later   [Release: and later ]
Information in this document applies to any platform.
Symptoms

Following errors in the alert.log file:

ORA-12012: error on auto execute of job "ORACLE_OCM"."MGMT_CONFIG_JOB_2_1"
ORA-29283: invalid file operation
Cause

The CM database job is out of sync with the OCM



Solution

This messages happen because of the OCM collection database job is unable to access the directory location where the OCM data is written .


If you using OCM to upload collection to My Oracle Support please re instrument the database:

1. export ORACLE_HOME=<path to the database home>
    export ORACLE_SID=<Database SID>

2.  Please remove the OCM configuration in the database:

     cd $ORACLE_HOME/ccr/bin
     ./configCCR -r

3. Please configure the OCM configuration in the database:

    ./configCCR -a <CSI> <MyOracleSupport ID>

4.  Instrument the Database:

     cd /ccr/admin/scripts
     ./installCCRSQL.sh collectconfig -s <SID> -r SYS

5.  Run a manual collection:

    cd $ORACLE_HOME/ccr/bin
    ./emCCR collect

If you do not use OCM delete the OCM configuration from the database:

Log in to your database as user SYS and drop-cascade user ORACLE_OCM:
SQL> DROP USER ORACLE_OCM CASCADE;

Error to start dbconsole in Oracle 10gR2 on AIX

Error to start dbconsole. Getting Following error while running dbca

Could not complete the Enterprise Manager configuration.
Enterprise manager configuration failed due to the following error -
Error starting Database Control

Metalink note suggests it is due to CS certificate expired, Need to apply Patch 8350262

redo log file move SQL commands.txt

ALTER DATABASE RENAME FILE '/gfsredo1/OASTDB/onlinelog/t1_mf_3_7yzxyt3y_.log' TO '/gfsdb/OASTDB/onlinelog/o1_mf_3_7yzxyt3y_.log';
ALTER DATABASE ADD LOGFILE MEMBER '/gfsredo1/OASTDB/onlinelog/redo1.log' TO GROUP 2;

Migrate VOTE and OCR ASM disk in Oracle

Migrate VOTE and OCR ASM disk in Oracle

To migrate OCR

ocrconfig add +OCR
ocrconfig delete +DATA
ocrcheck

To migrate Votedisk

crsctl replace css votedisk +VOTE
crsctl css query votedisk



Move Redo log file to other ASM Diskgroup.txt

alter system set db_create_online_log_dest_1='+REDODG1' scope=spfile;

select l.group# , l.bytes , l.status , lf.member from v$logfile lf , v$log l where lf.group# = l.group#;
show parameter db_create_file_dest;

select name,group_number from v$asm_diskgroup;

show parameter db_create_online_log_dest_1;
alter system set db_create_online_log_dest_1='+REDODG1' scope=spfile;


alter database drop logfile group 1;
alter database drop logfile group 2;
alter database drop logfile group 3;
alter database drop logfile group 4;
alter database drop logfile group 5;
alter database drop logfile group 6;
alter database drop logfile group 7;
alter database drop logfile group 8;

alter database add logfile group 1 size 1073741824;
alter database add logfile group 2 size 1073741824;
alter database add logfile group 3 size 1073741824;
alter database add logfile group 4 size 1073741824;
alter database add logfile group 5 size 1073741824;
alter database add logfile group 6 size 1073741824;
alter database add logfile group 7 size 1073741824;
alter database add logfile group 8 size 1073741824;

alter system switch logfile;


CRS-5008: Invalid attribute value: en1 for the network interface

Cluster Verification check "CRS Integrity" succeeded on nodes: rac11,rac12.
This test checks the integrity of Oracle Clusterware stack across the cluster nodes.
PRVF-4555 : Node application "ora.xxxx.vip" does not exist on node "rac12"PRVF-4557 : Node application "ora.net1.network" is offline on node "rac12"
PRVF-4557 : Node application "ora.xxxx.vip" is offline on node "rac11"PRVF-4557 : Node application "ora.net1.network" is offline on node "xxxx"
Cluster Verification check failed on nodes: xxx,yyy.
This test checks the existence of Node Applications on the system.
Cluster Verification check "Time zone consistency" succeeded on nodes: xxx,yyy.
This task checks for the consistency of time zones across systems.

Unique database identifier check passed.
Validation of server pool succeeded.
Scan listener is not running from Grid Infrastructure home.
Default Listener "LISTENER" is not configured in the Grid Infrastructure home.

/gfsdb/ is  shared across the cluster nodes.
/gfsdb/ has enough space. Required space is 1749 MB , available space is 40759 MB.
File Validations Successful.



2013-08-02 09:17:49.740: [ora.net1.network][2340] {1:40226:380} [start] subnetnumber=192.xx.xx.0
2013-08-02 09:17:49.740: [   AGENT][2340] {1:40226:380} UserErrorException: Locale is
2013-08-02 09:17:49.741: [ora.net1.network][2340] {1:40226:380} [start] Agent::commonStart Exception UserErrorException
2013-08-02 09:17:49.741: [   AGENT][2340] {1:40226:380} UserErrorException: Locale is AMERICAN_AMERICA.US7ASCII
2013-08-02 09:17:49.741: [   AGENT][2340] {1:40226:380} UserErrorException: Locale is
2013-08-02 09:17:49.741: [   AGENT][2340] {1:40226:380} UserErrorException: Locale is AMERICAN_AMERICA.US7ASCII
2013-08-02 09:17:49.742: [ora.net1.network][2340] {1:40226:380} [start] clsnUtils::error Exception type=2 string=
CRS-5017: The resource action "ora.net1.network start" encountered the following error:
CRS-5008: Invalid attribute value: en1 for the network interface


Reason
Mismatch in OCR and OS SUBNETMASK or SUBNETNUMBER

Solution
Check the subnet registered on OCR

/grid/bin/crsctl status resource ora.net1.network -p


confirm with the interface on OS
ifconfig <interface_name>

Change the value at OCR by following commands

/grid/bin/srvctl config nodeapps -a
oracle@rac11:/home/oracle/abhishek/bin > /grid/bin/srvctl config nodeapps -a
Network 1 exists
Subnet IPv4: 192.xxx.xxx.0/255.255.255.0/en1, dhcp
Subnet IPv6:
VIP exists: network number 1, hosting node rac11
VIP IPv4 Address: -/rac11-vip/192.xxx.xxx.xxx
VIP IPv6 Address:
root@rac11:/home/oracle/abhishek/bin > /grid/bin/srvctl modify nodeapps -n rac11 -A 192.xxx.xxx.xxx/255.255.252.0/en1
root@rac11:/home/oracle/abhishek/bin > /grid/bin/srvctl modify nodeapps -n rac12 -A 192.xxx.xxx.xxx/255.255.252.0/en1

Confirm with command

/grid/bin/crsctl status resource ora.net1.network -p