Tag Archives: NULL

Read sequence file into linked list in C.

By yifangt

Sounds like a homework, but not! This is only for self study. I know the better way would be in perl which is too slow if the file is too big (normally ~15GB), but I am trying to pick up C said to be more faster and use less memory. Can someone help me with my code? Here’s the file (which is a typical fastq format—mean every four lines as a unit): infile.txt

Code:

@Mseq1
AGCTG
+
XX%%A
@Mseq2
AGCGG
-
&X#%A
@Mseq3
AGCCG
+
#X%#A


Desired Output: outfile.txt

Code:

@Mseq1 AGCTG + XX%%A
@Mseq2 AGCGG - &X#%A
@Mseq3 AGCCG + #X%#A


Code:

#include
#include
#include

struct node
{
char readName[251];
char readSeq[251];
char strand;
char readQual[251];
struct node *next;
};

int main ()
{
FILE *fp;
int count;
char *line;
count = 1;
char filename[30] = "infile.txt";
struct node *read, *pre, *p;
struct node *first = NULL;

fp = fopen (filename, "r");

while (fgets (line, sizeof (line), fp) != NULL) /* read a line */
{
read = (struct node *) malloc (sizeof (struct node));
while (count % 4 == 1)
{
strcpy (read->readName, line);
}
count++;
while (count % 4 == 2)
{
strcpy (read->readSeq, line);
}
count++;
while (count % 4 == 3)
{
strcpy (read->strand, line);
}
count++;
while (count % 4 == 0)
{
strcpy (read->readQual, line);
}
count++;
read->next = NULL;
pre = p = first;

while (p != NULL)
{
pre = p;
p = p->next;
}
if (pre != NULL)
pre->next = read;
else
first = read;

fclose (fp);

...read more

Source: FULL ARTICLE at The UNIX and Linux Forums

Get pointer for existing device class (struct class) in Linux kernel module

By hdaniel@ualg.pt

Hi all!

I am trying to register a device in an existing device class, but I am

having trouble getting the pointer to an existing class.
I can create a class in a module, get the pointer to it and then use

it to register the device with:

*cl = class_create(THIS_MODULE, className);
dev_ret = device_create(*cl, NULL, *dev, NULL, driverName);

However I need to register another device in the same class with

another module, but I couldn’t find a way to get the pointer to an

existing class. And I can not crete the class again in the other

module, because since class already exists class_create() returns NULL

and not the pointer to the class required by device_create().

I found in a function that returns a pointer to a class by its name googling (sorry system did not allowed to post url)

struct class * class_find(char * name)

However when I try to compile the function compiler says it does not exist.
I thougth this function was exported by the kernel (my module have
license GPL) but it appears it is not.
Maybe I need to include some header?

I know its a patch I suposed it was in main stream kernel already.
I tried to rewrite this function since the code is available. The code is:

+struct class * class_find(char * name)
+{
+ struct class * this_class;
+
+ if (!name)
+ return NULL;
+
+ list_for_each_entry(this_class, &class_subsys.kset.list, subsys.kset.kobj.entry) {
+ if (!(strcmp(this_class->name, name)))
+ return this_class;
+ }
+
+ return NULL;
+}

But when I try to iterate over class_subsys with:

list_for_each_entry(this_class, &class_subsys.kset.list, subsys.kset.kobj.entry)

now symbol class_subsys is not found. Again I thougth it is exported

to the kernel.

I am not sure what is missing. Some header?
Am I doing it the wrong way?
There is another function to do it?

I supose if I could traverse sysfs from start I could get a pointer to an existing class.
But I also did not find how to start traversing sysfs.
All functions I have seen requires a pointer to kobject or kset to

start traversing. But I have no poniter even to the root of sysfs or kernel objects, so I can not start traversin the tree to get a class pointer.

Can anyone point me in the right direction please?

From: http://www.unix.com/unix-advanced-expert-users/221699-get-pointer-existing-device-class-struct-class-linux-kernel-module.html

Clients – Server ( UDP )

By MaHmur

Hello,

I have a question: I want to create a n client to one server connection. This is the client-server algorithm.

Quote:

#include
#include
#include
#include
#include
#include
#include
#include

const int PORT_SERVER=9001;
const int CLIENT_MAXIM=10;

extern int errno;
int ds;
int dc;
int nr=0;

void semna(int nr_semnal)
{ if(nr_semnal == SIGCHLD)
{ wait(NULL);
nr–;
return; }
}

int e_prim(int i)
{ int k;
for(k=2; k*k<=i;k++)
if(i%k==0)
return 0;
return 1;
}

void client()
{ char buffer[100];
char aux[100];
int i,t;
int numar, k;
sprintf(aux, “Este clientul numarul: %dn”, nr);
if(write(dc,aux,strlen(aux)) != strlen(aux))
{ shutdown(dc,2);
exit(errno); }
sprintf(aux, “Dati numarul:”);
if(write(dc,aux,strlen(aux)) != strlen(aux))
{ shutdown(dc,1);
exit(errno); }
bzero(buffer,100);

if(read(dc,buffer,100) == 0)
{ shutdown(dc,2);
exit(errno); }
numar=atoi(buffer);
for(k=2;k<numarl;k++)
if(e_prim(k))
{ sprintf(aux, “Numar prim: %dn”,k);
if(write(dc,aux,strlen(aux)) != strlen(aux))
{ shutdown(dc,2);
exit(errno); }
}
shutdown(dc,2);
exit(errno);
}

int main()
{ struct sockaddr_in server;
if(signed(SIGCHLD, semnal) == SIG_ERR)
{ perror(“signal()”);
exit(errno); }
if(signal(SIGPIPE, SIG_IGN) == SIG_ERR)
{ perror(“signal()”);
exit(errno); }
if((ds = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{ perror(“socket()”);
return errno; }
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT_SERVER);
server.sin_addr.s_addr=htonl(INADDR_ANY);

if(bind(ds,&server,sizeof(server)) == -1)
{ perror(“bind()”);
return errno; }
if(listen(ds,5) == -1)
{ perror(“listen()”);
return errno; }
printf(“Asteptam clientul la portul %d … n”, PORT_SERVER);
while(1)
{ dc=accept(ds,NULL,NULL);
if(nr == CLIENTI_MAXIM)
{ shutdown(dc,2);
continue; }
switch(fork())
{ case 0:
client();
break;
case -1:
perror(“fork()”);
break;
default:
break; }
nr++; }
}


Enybody help to make the changes?

From: http://www.unix.com/programming/221159-clients-server-udp.html

Serial programming using termios

By turner

Hi guys
I’m trying to connect to CISCO router using termios. So I decided to have two threads one for reading data and the other one for writing data.
And here’s my code :

Code:

int mainfd=0;
char ch[2] = {NULL};

void *write(void *)
{
char temp;
while(1)
{
temp = getchar();
ch[0] = temp; ch[1] = '';
if(temp == '~')
{
printf("connection closed.rn");
close(mainfd);
pthread_exit(NULL);
}
check=write(mainfd, ch, 1);
ch[0]='';
}
}

void *read(void *)
{
char outputbuffer[10000]= {0};
while(1)
{
outputbuffer[0]='';
int charnumber=read(mainfd, &outputbuffer, sizeof(outputbuffer));
outputbuffer[charnumber] = '';
printf("%s",outputbuffer);
outputbuffer[0] = '';
}
}

int main(int argc,char *argv[])
{
//////////////////
struct termios old = {0};
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
//////////////////
struct termios options;
static int portnum=atoi(argv[1]);

mainfd = open_port(portnum);

fcntl(mainfd, F_SETFL, FNDELAY);
tcgetattr(mainfd, &options);
cfsetspeed(&options, speed);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag |= CSTOPB;

options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
...read more
Source: FULL ARTICLE at The UNIX and Linux Forums

Help with linked list.

By prinsh

#include
#include

struct LinkedList
{
int val;
struct LinkedList *next;
}node;
typedef struct LinkedList Node;
Node *start = NULL;
int create(int i)
{
Node *temp = NULL;
if (start == NULL)
{
start = (Node*)malloc(sizeof(node));
start->val = i;
start->next=NULL;
return 0;
}
else
temp = start;
while(temp != NULL)
{
printf(“Value in temp = %dn”, temp->val);
temp=temp->next;
}
temp = (Node*)malloc(sizeof(node));
temp->val = i;
start->next= temp;
temp->next = NULL;
return 0;
}

void display()
{
Node *temp = NULL;
printf(“Displaying Listn“);
if (start == NULL)
printf(“List is Emptyn”);
else
{
temp = start;
while(temp != NULL)
…read more
Source: FULL ARTICLE at The UNIX and Linux Forums

Psql replace blanks with character

By wxornot

Well as the title describes, its a pretty straight forward problem. I have a series of psql tables where there are lots of blanks. However there is at least one column, called name, that will never be blank. I want to write a select statement to get all of the contents of the table and then turn blanks into a string like NULL. Here is my select statement idea, but I just don’t have a strong enough grasp on how the statement should look:



SELECT name,date,value
FROM table
WHERE value=’ ‘ print as “NULL“;

I don’t want to update the actual table, just print it without blanks. Obviously the above code doesn’t work, but hopefully you get the idea. I appreciate the help.

Dave

Source: FULL ARTICLE at The UNIX and Linux Forums

And now for something old… Plouf!

This is by far my longest release ever: 18 years!

18 years ago I was learning the ropes of coding on an Amiga 500. Using
AMOS, a game-oriented Basic, I played with creating games and demos. I was
not as persevering as nowadays: most of those creations got started and
abandoned a few weeks later, but I did manage to finish one of those game
attempts: Plouf!

The game

Plouf! is a top-down game where players sit on floats, trying to sink the other
players by throwing sea urchins at them. “Plouf!” is the French onomatopoeia
for the sound made by an object when it falls into a liquid.

You control your float like an RC car: you can accelerate, slow down and rotate
left or right. The islands on the screen are randomly generated, so each game
looks different.

It only support 2 or 3 players: I didn’t have the skills to code a computer
player by then.

You start with a very limited number of sea urchins, so you need to collect them
as they appear randomly in the sea. You can also grab float bonuses which
increase the strength of your float by one point.

Here are some screenshots:

The start screen

The start screen

A 2 player game, blond guy has just thrown a sea urchin, but it's going to miss its target

A 2 player game, blond guy has just thrown a sea urchin, but it’s going to miss its target

A 3 player game starting

A 3 player game starting

First release

I released Plouf! as a shareware in 1994: a floppy disk of the demo version
(limited to 4 games) could be obtained from a few Amiga freeware and shareware
floppy disk dealers (this was a time where Internet was not ubiquitous…)

It sold the impressive number of 0 full versions 🙁 Playing with friends is a
lot of fun, but I guess the lack of a single-player mode was a show stopper.

Fast forward

Some time ago I decided to release it as free software. I bought a NULL-modem
cable and transfered the source code to my laptop.

There was one problem though: all text was in French 🙁 I wanted to at least
translate all visible strings to English. One would think it would just be a
matter of opening the source code with a modern editor and run the AMOS
Compiler to regenerate binaries… It’s not that simple: the format of .AMOS
files is binary: it bundles the source code and the program assets. This means
it can only be edited with AMOS Editor. I thus ran AMOS Editor in UAE to do all
my edits… I can confirm editors have made a lot of progress since 1994…

Editing Plouf! source code with AMOS

Nevertheless, it was a lot of fun to use these tools again. I eventually
managed to figure out again how everything worked. I translated the visible
strings (note that I didn’t went as far as translating the source code),
adjusted a few other things and here it is: Plouf! is released under GPL 3 or
later license!

Playing Plouf!

To play Plouf! you first need to download plouf-1.1.adf. Then either you are
the lucky owner of an Amiga and you know how to transfer it on a disk to use on
your machine, or you don’t have an Amiga and you can run it with an Amiga
emulator.

If you want to give it a try on an emulator, I recommend FS-UAE, a user-friendly
fork of UAE, with a nicely done frontend.

Source code

The source code is available from github: https://github.com/agateau/plouf.
Just keep in mind you can’t really read it online since the .AMOS files are
not text files.

Flattr this

Source: FULL ARTICLE at Planet KDE

Rocks cluster 6.1 and MPICH2 problem??????

By gabam

Hey friends,
I am trying to execute a simple hello world in mpi on MPICH2 on Rocks cluster. here is the c source code.

Code:


#include
#include
int main( int argc, char ** argv )
{
MPI_Init( NULL, NULL );
int world_size;
MPI_Comm_size( MPI_COMM_WORLD, &world_size );
int world_rank;
MPI_Comm_rank( MPI_COMM_WORLD, &world_rank );
char processor_name[MPI_MAX_PROCESSOR_NAME];
int name_len;
MPI_Get_processor_name( processor_name, &name_len );
printf( "Hello world from processor %s, rank %d" " out of %d processorsn", processor_name, world_rank, world_size );
MPI_Finalize();
}


And I compile it like this.

Code:

/opt/mpich2/gnu/bin/mpicc ./hello.c -o hello


I have the following entry on the machine file.

Code:

compute-0-0
compute-0-1


Now here is how I run the hello program

Code:

/opt/mpich/gnu/bin/mpirun -np 2 -machinefile machines ./hello


which gives me the follwing error.

Code:


[user1@cluster ~]$ /opt/mpich2/gnu/bin/mpirun -np 2 -machinefile machines ./mpi_hello_world
Could not chdir to home directory /export/home/user1: No such file or directory
Could not chdir to home directory /export/home/user1: No such file or directory
[proxy:0:0@compute-0-0.local] launch_procs (./pm/pmiserv/pmip_cb.c:687): unable to change wdir to /export/home/user1 (No such file or directory)
[proxy:0:0@compute-0-0.local] HYD_pmcd_pmip_control_cmd_cb (./pm/pmiserv/pmip_cb.c:935): launch_procs returned error
[proxy:0:0@compute-0-0.local] HYDT_dmxu_poll_wait_for_event (./tools/demux/demux_poll.c:77): callback returned error status
[proxy:0:0@compute-0-0.local] [mpiexec@cluster.hpc.org] control_cb (./pm/pmiserv/pmiserv_cb.c:215): assert (!closed) failed
[mpiexec@cluster.hpc.org] HYDT_dmxu_poll_wait_for_event (./tools/demux/demux_poll.c:77): callback returned error status
[mpiexec@cluster.hpc.org] HYD_pmci_wait_for_completion (./pm/pmiserv/pmiserv_pmci.c:181): error waiting for event
[mpiexec@cluster.hpc.org] main (./ui/mpich/mpiexec.c:405): process manager error waiting for completion
[user1@cluster ~]$


Please help me.

Source: FULL ARTICLE at The UNIX and Linux Forums

Can't debug: assert error with gdb (no problem without)

By erupter

I’m sorry if the title is really criptic, but I don’t know how to phrase my problem.

I know I can’t really ask for a solution, and I normally wouldn’t but this is really escaping my abilities.

Antefacts.
I developed a program using the zeromq messaging library.
I got to a point where the program works and then started going multithreading: moving a message poller outside of the main thread.
This is supported by the library.
So I devised my thread, passed it a pointer to some parameters (including the pointer to the zmq context) and went ahead.

The Problem
The code in the child thread is the same code I had in the parent, save for the facts that functions parameters are stored in a structure that gets passed to the child.
I followed every function in the child and the parameters are correct.
The code does even work (as it should) when run normally, but hangs with an assert when run in debug.

I tried following every function I could, built the library with debug symbols, using gdb from the console…

I got nothing useful.
I still don’t understand why it fails with the debugger attached, and why it runs without.

The culprit code is the following

Code:

if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
pgm_error->domain == PGM_ERROR_DOMAIN_IF) && (
pgm_error->code != PGM_ERROR_INVAL &&
pgm_error->code != PGM_ERROR_BADF &&
pgm_error->code != PGM_ERROR_FAULT))


from pgm_socket.cpp:301
And here are a couple gdb outputs

Code:

Breakpoint 1, zmq::pgm_socket_t::init (this=0x7ffff0000930,
udp_encapsulation_=true, network_=) at pgm_socket.cpp:301
warning: Source file is more recent than executable.
301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb) stepi
0x00007ffff786488d 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff786488f 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff7864891 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff7864894 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff7864896 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff7864899 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff786489c 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff786489e 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff78648a1 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff78648a3 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
0x00007ffff78648a6 301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb)
376 if (sock != NULL) {
(gdb)


Code:

Breakpoint 1, zmq::pgm_socket_t::init (this=0x7ffff0000930,
udp_encapsulation_=true, network_=) at pgm_socket.cpp:301
301 if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET ||
(gdb) step
376 if (sock != NULL) {
(gdb)
377 pgm_close (sock, FALSE);
(gdb)


There is supposedly no way (and no reason) to jump from line 301 to 376, yet it happens.
After that there is a

Code:

return -1;


that triggers the assert that kills my code.

And I’m banging my head over this without so much as a hope of understanding what to do.

I can’t really hope for a solution with this, but at least a suggestion as to how to proceed.

My code (if anyone really wanted to check it out) on github is under the project “saettang“.

Source: FULL ARTICLE at The UNIX and Linux Forums

Running C++ like shell script

By SkySmart

i found the following code off the web. its suppose to read large log files, efficiently. but i dont have an idea of how to run it. i know its C and you need to “compile”. how do i compile it? and is it really necessary to compile?

Code:

/*
** File FILE_3.C
**
** Illustrates how to read from a file.
**
** The file is opened for reading. Each line is successively fetched
** using fgets command. The string is then converted to a long integer.
**
** Note that fgets returns NULL when there are no more lines in the file.
**
** In this example file ELAPSED.DTA consists of various elapsed times in
** seconds. This may have been the result of logging the time of events
** using an elapsed time counter which increments each second from the
** time the data logger was placed in service.
**
** Typical data in elapsed.dta might be;
**
** 65
** 142
** 1045
** 60493
** 124567
**
**
** Peter H. Anderson, 4 April, '97
*/

#include /* required for file operations */
#include /* for clrscr */
#include /* for delay */

FILE *fr; /* declare the file pointer */

main()

{
int n;
long elapsed_seconds;
char line[80];
clrscr();

fr = fopen ("elapsed.dta", "rt"); /* open the file for reading */
/* elapsed.dta is the name of the file */
/* "rt" means open the file for reading text */

while(fgets(line, 80, fr) != NULL)
{
/* get a line, up to 80 chars from fr. done if NULL */
sscanf (line, "%ld", &elapsed_seconds);
/* convert the string to a long int */
printf ("%ldn", elapsed_seconds);
}
fclose(fr); /* close the file prior to exiting the routine */
} /*of main*/


i would think a code like this can be saved in a file called code.sh. and just run from the command line like this:

Code:

./code.sh filename


but of course, that may be wishful thinking.

Source: FULL ARTICLE at The UNIX and Linux Forums

Reading a router configuration file

By digidaxHello C specialists,

I’m trying to write a program to read out a binary configuration file produced by a router.
But the output of Name and Value is cryptic. What’s going wrong?

The structure of the binary file is very simple:

struct nvram_tuple {
char *name;
char *value;
struct nvram_tuple *next;
};

Please see attached file with detailed used headers and sources.

Here the code:

Code:
#include
#include
#include
#include “bcmnvram.h”
#include “typedefs.h”

int main(int argc, char *argv[])
{

struct nvram_tuple *srouter_defaults = NULL;
static unsigned int defaultnum;

FILE *in = fopen(“defaults_fmk.bin”, “rb”);

if (in == NULL)
{
printf(“ERROR: Cant open filenn”);
system(“PAUSE“);
return 1;
}

defaultnum = (unsigned int)getc(in);
defaultnum |= (unsigned int)getc(in)
Source: The UNIX and Linux Forums

This code keeps giving me a segmentation fault why?

By fwrlfo
Code:
#include
#include
#include “tlpi_hdr.h”
#include
static volatile int glob = 0;

static struct {
pthread_t t1,t2;
} *thread;

static void * /* Loop ‘arg’ times incrementing ‘glob’ */
threadFunc(void *arg)
{

int loops = *((int *) arg);
int loc, j, s;

if (s != 0)
errExitEN(s, “pthread_mutex_lock”);
for (j = 0; j 1) ? getInt(argv[1], GN_GT_0, “num-loops”) : 10000000;
s = pthread_create(&thread[loops].t1, NULL, threadFunc, &loops);
if (s != 0)
errExitEN(s, “pthread_create”);
s = pthread_create(&thread[loops].t2, NULL, threadFunc, &loops);
if (s != 0)
errExitEN(s, “pthread_create”);
s = pthread_join(thread[loops].t1, NULL);
if (s != 0)
errExitEN(s, “pthread_join”);
s = pthread_join(thread[loops].t2, NULL);
if (s != 0)
errExitEN(s, “pthread_join”);
printf(“final glob = %dn”, glob);
exit(EXIT_SUCCESS);
}

Source: The UNIX and Linux Forums

Colin King: Striving for better code quality.

Software is complex and is never bug free, but fortunately there are many different tools and techniques available to help to identify and catch a large class of common and obscure bugs.

Compilers provide build options that can help drive up code quality by being particularly strict to detect questionable code constructions, for example gcc’s -Wall and -pedantic flags.  The gcc -Werror flag is useful during code development to ensure compilation halts with an error on warning messages, this ensures the developer will stop and fix code.

Static analysis during compilation is also a very useful technique, tools such as smatch and Concinelle can identify bugs such as deferencing of NULL pointers, checks for return values and ranges,  incorrect use of && and ||, bad use of unsigned or signed values and many more beside.  These tools were aimed for use on the Linux kernel source code, but can be used on C application source too.  Let’s take a moment to see how to use smatch when building an application.

Download the dependencies:
sudo apt-get install libxml2-dev llvm-dev libsqlite3-dev

Download and build smatch:
mkdir ~/src
cd ~/src
git clone git://repo.or.cz/smatch
cd smatch
make

Now build your application using smatch:
cd ~/your_source_code
make clean
make CHECK=”~/src/smatch/smatch –full-path”
CC=~/src/smatch/cgcc | tee warnings.log

..and inspect the warnings and errors in the file warnings.log.  Smatch will produce false-positives, so not every warning or error is necessarily buggy code.

Of course, run time profiling of programs also can catch errors.  Valgrind is an excellent run time profiler that I regularly use when developing applications to catch bugs such as memory leaks and incorrect memory read/writes. I recommend starting off using the following valgrind options:
–leak-check=full –show-possibly-lost=yes –show-reachable=yes –malloc-fill=

For example:
valgrind –leak-check=full –show-possibly-lost=yes –show-reachable=yes
–malloc-fill=ff your-program

Since the application is being run on a synthetic software CPU execution can be slow, however it is amazingly thorough and produces detailed output that is extremely helpful in cornering buggy code.

The gcc compiler also provides mechanism to instrument code for run-time analysis.  The -fmudflap family of options instruments risky pointer and array dereferencing operations, some standard library string and heap functions as well as some other range + validity tests.   For threaded applications use -fmudflapth instead of -fmudflap.   The application also needs to be linked with libmudflap.

Here is a simple example:
int main(int argc, char **argv)
{
static int x[100];
return x[100];
}

Compile with:
gcc example.c -o example -fmudflap -lmudflap

..and mudflap detects the error:
./example
*******
mudflap violation 1 (check/read): time=1347817180.586313 ptr=0x701080 size=404
pc=0x7f98d3d17f01 location=`example.c:5:2 (main)’
/usr/lib/x86_64-linux-gnu/libmudflap.so.0(__mf_check+0x41) [0x7f98d3d17f01]
./example(main+0x7a) [0x4009c6]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed) [0x7f98d397276d]
Nearby object 1: checked region begins 0B into and ends 4B after
mudflap object 0x190a370: name=`example.c:3:13 x’
bounds=[0x701080,0x70120f] size=400 area=static check=3r/0w liveness=3
alloc time=1347817180.586261 pc=0x7f98d3d175f1
number of nearby objects: 1

These are just a few examples, however there are many other options too. Electric Fence is a useful malloc debugger, and gcc’s -fstack-protector produces extra code to check for buffer overflows, for example in stack smashing. Tools like bfbtester allow us to brute force check command line overflows – this is useful as I don’t know many developers who try to thoroughly validate all the options in their command line utilities.

No doubt there are many more tools and techniques available.  If we use these wisely and regularly we can reduce bugs and drive up code quality.

Source: Planet Ubuntu

*log to *.csv in perl

By frhlingI want to convert the log files to xls. by bash script I converted it to csv, but I need to make some changes in some of them. please dont ask why xls and not csv. I need xls and this is to be a automated process.
I am new to linux, bash and NULL in Perl.
That would be nice if someone help me to convert to xls 🙂
this is my code in bash scripting which converts log to csv. Now I want log to xls.

#!/bin/bash
NAME=evaluation_`date +%Y%m%d`
find /dir -name “*.log” -mtime 0 -exec cat “{}” ; >> $NAME.log
grep -e word1 -e word2 $NAME.log | grep -v word3| awk ‘{n=split($11,P,”/”);print $1 ” ” $2 “;” $3 “;” $9 “;” $11 “;” P[n]}’ > $NAME.csv

sed -i ‘1iDate;Time;From;To;User’ $NAME.csv

rm $NAME.log

echo “done.”

Source: The UNIX and Linux Forums

C- static initialization of structures

By garyskSituation:
I have an array of structures:
Code:
struct my_struct_type {
char tags_sn[5];
char group_c;
char is_err_c;
};
struct my_struct_type stuff[] = {
“abcd”, ‘A’, ‘E’,
“efgh”, ‘B’, ‘E’,
“ijkl”, ‘C’, ‘E’
NULL, ”, ”
};
This compiles under gcc.

Code:
% gcc -v
Using built-in specs.
Target: hppa2.0w-hp-hpux11.23
Configured with: ../gcc/configure
Thread model: posix
gcc version 4.2.3
% uname -a
HP-UX warthog B.11.23 U 9000/800 1173444606 unlimited-user license
In a loop that uses tags_sn == NULL as its terminating condition, it fails to terminate and instead of course gets a segmentation violation and dumps core. After pulling out of hair for a while, I realize that I have just initialized an array (constant address) with NULL. But wait! Why does the compiler allow me to say (essentially) tags_sn = NULL;? You can’t just assign an integer, or even an integer cast as a pointer, to an array, can you? An array is a constant address. You can’t assign to a constant; it’s constant!

Why does this compile?

I’ve been programming in C professionally since 1984. My dog-eared K&R says trying to assign to an array address is a no-no.

Changing the structure declaration to char *tags_sn; makes everything happy. This is clearly my error, but isn’t the compiler supposed to catch dumb errors like this?

Final question: when the (implied) code char tags_sn[5]; tags_sn = NULL; compiles, what does it do?
Source: The UNIX and Linux Forums

Calling functions from main program from dlopened library function

Hello All,

I am trying to call a function from the calling main program from a dlopened library function, below is the entire code, when I execute it it crashes with sigill. Can you guys help me out I guess I am missing out on the linker flag or something here. besides I am new to AIX and really appreciate your help on this.

Code:
# cat main.c
#include
#include
#include
#include
typedef void (*FP)(void);

void printme (void) {
printf (“printed me hurray!!!n”);
}

int
main( int argc, char** argv )
{
void* handle;
void* symptr;
FP fp;
/*** Load the shared object containing the definition of the ***/
/*** function . defsym(). ***/
if ( NULL == ( handle = dlopen( “./libdefsym.so”, RTLD_NOW ) ) ){
perror( dlerror() );
exit( 1 );
}
/**** Obtain the address of the function defsym. ***/
if ( NULL == ( symptr = dlsym( handle, “defsym” ) ) ) {
if ( 0 == errno ) {
fprintf( stderr, “Symbol defsym not found. Exitingn”
);
exit( 1 );
}
perror( dlerror() );
exit( 1 );
}
fp = ( FP )symptr;
/*** Call the function via the obtained function address. ***/
fp();
/*** Unload the previously loaded shared object. ***/
if ( 0 != ( dlclose( handle ) ) ) {
perror( dlerror() );
exit( 1 );
}
exit( 0 );
}

defsym.c
#include
#include
void
defsym()
{
printf( “defsym called.n” );
printme();
}

cat toexp.exp
#!.
printme

Makefile
CC=gcc
CFLAGS= -g -maix64
all: main libdefsym.so
main: main.o
$(CC) -maix64 -o main main.o
main.o: main.c
$(CC) $(CFLAGS) -c main.c
libdefsym.so: defsym.o
ld -G -bnoentry -bexpall -bE:toexp.exp -o libdefsym.so defsym.o -lc
defsym.o: defsym.c
$(CC) $(CFLAGS) -c defsym.c
.PHONY: clean
clean:
rm *.o *.so main

# dbx ./main core
Type ‘help’ for help.
[using memory image in core]
reading symbolic information …internal error: 1283-228 expected char ‘,’, found ‘;-31,448,256;;’
internal error: 1283-228 expected char ‘;’, found ‘,256;;’
internal error: 1283-232 index(“256;;”, ‘:’) failed
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: 1283-228 expected char ‘,’, found ‘s__LC_locale:,1088,64;__meth_ptr:13,1152,64;__data_ptr:13,1216,64;;’
internal error: 1283-228 expected char ‘,’, found ‘__LC_locale:,1088,64;__meth_ptr:13,1152,64;__data_ptr:13,1216,64;;’
internal error: 1283-228 expected char ‘;’, found ‘_LC_locale:,1088,64;__meth_ptr:13,1152,64;__data_ptr:13,1216,64;;’
internal error: unexpected value 44 at line 5176 in file stabstring.c
internal error: 1283-228 expected char ‘,’, found ‘1088,64;__meth_ptr:13,1152,64;__data_ptr:13,1216,64;;’
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: 1283-228 expected char ‘,’, found ‘s_LC_locale_objhdl:,128,64;;’
internal error: 1283-228 expected char ‘,’, found ‘_LC_locale_objhdl:,128,64;;’
internal error: 1283-228 expected char ‘;’, found ‘LC_locale_objhdl:,128,64;;’
internal error: unexpected value 44 at line 5176 in file stabstring.c
internal error: 1283-228 expected char ‘,’, found ‘128,64;;’
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c

Illegal instruction (illegal opcode) in . at 0x0
warning: Unable to access address 0x0 from core
(dbx) where
.() at 0x0
internal error: 1283-228 expected char ‘,’, found ‘;-31,448,256;;’
internal error: 1283-228 expected char ‘;’, found ‘,256;;’
internal error: 1283-232 index(“256;;”, ‘:’) failed
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: 1283-228 expected char ‘,’, found ‘s__LC_locale:,1088,64;__meth_ptr:13,1152,64;__data_ptr:13,1216,64;;’
internal error: 1283-228 expected char ‘,’, found ‘__LC_locale:,1088,64;__meth_ptr:13,1152,64;__data_ptr:13,1216,64;;’
internal error: 1283-228 expected char ‘;’, found ‘_LC_locale:,1088,64;__meth_ptr:13,1152,64;__data_ptr:13,1216,64;;’
internal error: unexpected value 44 at line 5176 in file stabstring.c
internal error: 1283-228 expected char ‘,’, found ‘1088,64;__meth_ptr:13,1152,64;__data_ptr:13,1216,64;;’
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: 1283-228 expected char ‘,’, found ‘s_LC_locale_objhdl:,128,64;;’
internal error: 1283-228 expected char ‘,’, found ‘_LC_locale_objhdl:,128,64;;’
internal error: 1283-228 expected char ‘;’, found ‘LC_locale_objhdl:,128,64;;’
internal error: unexpected value 44 at line 5176 in file stabstring.c
internal error: 1283-228 expected char ‘,’, found ‘128,64;;’
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
internal error: unexpected value 120 at line 5176 in file stabstring.c
defsym(), line 8 in “defsym.c”
main(argc = 1, argv = 0x0ffffffffffff9e0), line 36 in “main.c”
(dbx)

Source: The UNIX and Linux Forums

Mysql++

code:
#include
#include
int main(int argc, char **argv)
{

MYSQL *conn;

conn = mysql_init(NULL);
mysql_real_connect(conn, “localhost”, “zetcode”, “passwd”, “testdb”, 0, NULL, 0);

mysql_query(conn, “use vobd_db”);

mysql_query(conn, “select * from obd_call_status limit 10”);

result = mysql_store_result(conn);
mysql_close(conn);

}
output :
mysql.c:2:23: error: my_global.h: No such file or directory
mysql.c: In function âint main(int, char**)â:
mysql.c:8: error: âNULLâ was not declared in this scope
mysql.c:15: error: âresultâ was not declared in this scope

can anyone wana try removing the errors
Source: The UNIX and Linux Forums