nezachem 616 Practically a Posting Shark

firstnode never changes. AddToList is passed the _value_ of firstnode (which is NULL), and operates on the local variable. Upon return, firstnode remains NULL.

You have to either pass an address of firstnode,

void AddToList(LankadLista ** listaptr, char name[])
{
    ...
    *listaptr = newnode;
    ...
}

main()
{
    ...
    AddToList(&firstnode, ...);
    ...
}

or return the modified local:

LankadLista * AddToList(LankadLista * lista, char name[])
{
    ...
    return lista;
}

main()
{
    ...
    firstnode = AddToList(firsnode, ...);
    ...
}
nezachem 616 Practically a Posting Shark

It is important to realize that the child process cannot possibly affect the parent's environment. When you run the command from the executable file, a second copy of bash is forked, it has its environment changed and then dies leaving no trace. The builtins (dot and source for example) are executed in the context of the current process, without forking a child, and the environment modifications stay put.
To make a simple one word command, you may wrap it in the function, and have that function in .bashrc, or some other autosourced file of your preference.

nezachem 616 Practically a Posting Shark

fgets() (line 15 of the original post) reads not only the command line, but a trailing newline as well. The newline is never stripped, and after tokenization it is still attached to the last argument. See an extra empty line (line 3):

/bin/ls /
/bin/ls    /
    
/bin/ls: cannot access /
: No such file or directory

That is, /bin/ls tries to access the "/\n" directory, which of course doesn't exist.

/bin/echo obviously doesn't care.

Ancient Dragon commented: good catch :) +33
nezachem 616 Practically a Posting Shark

A separate dll is not necessary. dlopen(0, ...) gives a handle to the main module.

sree_ec commented: good one +1
nezachem 616 Practically a Posting Shark

I see that the thread is solved. However, using __DATE__ and __TIME__ (which are stanadrd predefined macros) looks more straightforward...

nezachem 616 Practically a Posting Shark

Besides checking a return value, allocation is OK. Lines 22-24 look strange though. A simple

CircleP circleP = allocateMem();

is enough.

nezachem 616 Practically a Posting Shark

Your printing loop counter is j, but you print x.

nezachem 616 Practically a Posting Shark

The string returned by asctime contains an embedded colons and a newline, which are forbidden in Windows filenames.

nezachem 616 Practically a Posting Shark

1. Sed can address lines by numbers:

sed 1,3d

will do the job of your greps.

2. When inserting the comment, watch for an existing sharp:

/^[^#].*Watchdog/s/^/#/

3. You can issue multiple commands to a single sed invocation:

sed -e '1,3d' -e '/^[^#].*Watchdog/s/^/#/'

So, finally:

crontab -l | sed -e '1,3d' -e '/^[^#].*Watchdog/s/^/#/' > /tmp/crontab.a
egmik3 commented: Wow!! I love the help, so detailed and helps me learn sed +4
nezachem 616 Practically a Posting Shark

Before going into windchill, try the experiment, you'd be surprised:

tC = f2c(t);
    tF = c2f(tC);
    cout << "t = " << t << "; tF = " << tF << endl;

The printed out values should be identical. They are not.

Griff0527 commented: excelent testing code. I spotted the error in my c2f code almost immediately by using this +1
nezachem 616 Practically a Posting Shark

Yes it is possible, although I'd recommend automation via make and a shell script. For example, add two targets to a makefile:

simulate: NEW_file
    simulation command line here

NEW_file: binary_file
    reader command line here

( simulate target should be a default one).

If the simulation generates output, you may want to have that output file as another target.

nezachem 616 Practically a Posting Shark

One problem with this code is that it can't match a literal '?'. Another is its complexity. I can't even try to understand how it works, let alone debug it.
This is how I would approach globbing:

#include "glob.h"

int globMatch(char * pattern, char * text)
{
    while(*pattern && *text) {
        char p = *pattern++;
        switch(p) {
        case '*':
            while(*text) {
                int rc = globMatch(pattern, text++);
                if(rc != MATCH_FAIL)
                    return rc;
            }
            return MATCH_FAIL;
        case '\\':
            if((p = *pattern++) == 0)
                return MATCH_ERROR;
            if(p != *text++)
                return MATCH_FAIL;
            break;
        case '?':
            text++;
            break;
        default:
            if(p != *text++)
                return MATCH_FAIL;
        }
    }
    return ((*pattern == 0) && (*text == 0))? MATCH_SUCCESS: MATCH_FAIL;
}

with an obvious glob.h:

#ifndef _GLOB_H_
#define _GLOB_H_

#define MATCH_ERROR    -1
#define MATCH_SUCCESS   0
#define MATCH_FAIL      1
        
#ifdef cplusplus
extern "C" {
#endif          
int globMatch(char * pattern, char * text);
#ifdef cplusplus    
}           
#endif      
        
#endif
Zoon commented: Useful post +1
nezachem 616 Practically a Posting Shark

perror after line 13 can give some useful information.

AD: OP tries to open the file for writing; it doesn't matter if the file already exists or not.

Ancient Dragon commented: Oops! :) +28
nezachem 616 Practically a Posting Shark

Something is wrong here, don't you think?

print "test_string:\t%.4f" % timeMethod([B]test_string[/B], 10, 1000000)
print "test_stringIO:\t%.4f" % timeMethod([B]test_string[/B], 10, 1000000)
print "test_cStringIO:\t%.4f" % timeMethod([B]test_string[/B], 10, 1000000)
Gribouillis commented: Indeed ! +3
nezachem 616 Practically a Posting Shark

> note: previous implicit declaration of ‘findEntry’...LINE 15

The error message means that by the moment the compiler sees the use of the function, it didn't see neither its prototype nor definition. In such situation the compiler must guess how it should be prototyped, and usually it guesses wrong (it will presume that the function returns int).

Put the prototype somewhere above main(), and the error would go away.

nezachem 616 Practically a Posting Shark

> I suppose it depends on your perspective. If not having to call free feels like a straight jacket then we can word it in a bad way. If not having to call free feels liberating then we can word it in a good way. What's your take on garbage collection?

The announced goal of the io_gets is to handle very long strings. Therefore it feels that the library must be prepared to the out-of-memory condition. Now, what can be done in that situation? The answer is, absolutely nothing. Me the user can't call free, or face some unpleasantness at the atexit time. So, even though the pointers to allocated memory aren't technically lost, the memory itself is unusable. It becomes a well-managed memory leak.

Which brings another point to consider. Correct me if I am wrong, but the memory will be deallocated at the program exit time anyway. The memory pool library -as written - just takes over the system job, nothing more. The pooling would make sense only if it lets the user manage itself.

That said, you already disclaimed that the library is not complete.

kvprajapati commented: Good discussion and a point. +9
nezachem 616 Practically a Posting Shark

Just a few (very random) comments.

1. io_gets.c calls for #include <errno.h> . I realize it gets included through one of the headers anyway, but let's be explicit. BTW, why bother with errno at all? In this particular case it doesn't add anything which would help in recovery.
Besides, I firmly (and humbly) believe that a library function may resort to errno only if it can't possibly flag an error in any other way.

2. > does not force the caller to free the resulting pointer

I'd say, it forces the caller not to free it. I don't think it is right. The library should at least provide a way to reclaim unneeded strings. That said, I seriously doubt the value of deallocation at exit time.

3. > Storing the newline is unnecessary
Again, can't agree with this. It destroys a very valuable piece of information, namely, did io_gets return due to a newline, or due to an allocation failure. The way the code handles it (via errno) forces the caller to check errno after every call to io_gets. I don't think it is right.

nezachem 616 Practically a Posting Shark
class polygon{
  int n;
  point *points;
public:
  polygon(int n){
    point *points=new point[n];
    this->n=n;
  };

At the line 6 you initialize a local variable points . The member points remains uninitialized.

nezachem 616 Practically a Posting Shark

You have to clear() your stream.
When the line ends with the last number, a corresponding extract hits the end of string, and the stream is in end-of-file condition. Calling str() does not clear it.

nezachem 616 Practically a Posting Shark

Probably, you want to print(value) instead.

PS: note that subprocess.call returns the exit status, not the output. You may want to redirect stdout.

nezachem 616 Practically a Posting Shark

The value is just a pointer

... so it must oblige to the pointer alignment requirements. If the pointer is fetched correctly, the call would succeed. However, if it is stored at the odd boundary, chances are you'd fetch not what you expect.

This UB stems from the architectural issues indeed. On most IA32 based platforms you wouldn't notice anything strange. Still it is an UB and must be avoided.

gerard4143 commented: Thanks for the clear explanation +3
nezachem 616 Practically a Posting Shark
*(unsigned int*)&recvline[0] = 11111;

*(unsigned int*)&recvline[sizeof(unsigned int)] = 22222;
/*this section*/
*(void(**)(void))&recvline[2 * sizeof(unsigned int)] = (void(*)(void))&myhello;
/*this section*/

Casting is not for l-value. Only for r-value.

Correct, but not applicable. The result of cast, e.g. (int *) foo , is not an lvalue, and cannot be assigned. (int *) foo = bar; is incorrect. However, it can be indirected all right. * (int *) foo = baz; is perfectly OK.

Regarding the original post, though well-formed, the code may invoke an undefined behaviour. The alignment of unsigned int (and a function pointer) is stronger than that of a char; a situation specifically mentioned in 6.3.2.3.7 paragraph of a Standard.

jephthah commented: success +7
nezachem 616 Practically a Posting Shark

There's an example at the top of paragraph 20.11 (ftplib) of python documentation. See how a callback is passed to retrbinary. You need a similar setup for your ftp.dir() - or better ftp.retrlines('LIST', callback).

nezachem 616 Practically a Posting Shark

I was planning to write a long response. I was planning to write the same client-server pair myself (and I actually did) to prove that there's nothing wrong with the posted code, and that the problem lies somewhere outside of the fragments you presented.
But at the last moment I noticed a little problem, right there in the server fragment.

if((pid==fork())==0)

Highlighted in red.

Obviously, pid (however (un)initialized it is) does not compare equal to the value returned by fork(); the comparison is false, and both parent and child enter the if clause. That explains all the contradictions, weirdnesses, and inconsistencies in your system behaviour.

The most valuable lesson here is that an incomplete code is impossible to debug.
Even more valuable one is that meditative debugging doesn't worth a dam.

PS:

to use read instead of fgets, and that's my next step, could you please give me the syntax of the function

You already have used them to communicate through the socket. Use write(fileno(fp), buffer, aux) at client.c:12 and read(fileno(fp), archivo, 16) at server.c:13

mitrmkar commented: Nice +5
nezachem 616 Practically a Posting Shark

Your approach indeed doesn't work for non-integer exponents. It is just not applicable.
Check out Taylor series, or some other approximation.

nezachem 616 Practically a Posting Shark

it is a char array

You must realize that until you disclosed this vital piece of information all attempts to help were shots in the dark.

Now you may try to go with a

union u {
    unsigned long SomeLongArray[2];
    char SomeCharArray[8];
};

which will force the alignment, and avoid ugly casts.

nezachem 616 Practically a Posting Shark

I really don't understand how I can implement this function into cosi().

I don't think you should.
In my understanding (from the teacher's point of view), you have to prove somehow that your cosi indeed calculates cosine; in other words, that the values returned by cosi are close enough to the "golden standard" ones returned by cos from a math library.
That is, for each angle you have to calculate both cosi and cos , and feed the results to close_enough .
Yet again, it is my understanding; better check with your teacher.

jonsca commented: That was how I was interpreting it also... +4
nezachem 616 Practically a Posting Shark

One thing to add. A straightforward implementation of Taylor series, as in the post #3, quickly leads to numerical problems. A 32-bit integer cannot hold a factorial of numbers beyond 12, which essentially limits the series to the first six members (hence the line 54 of the original post).

A proper way to calculate series is a Horner schema, which allows for literally thousands of member, and never forces a calculation of unreasonable large numbers. Here's how it works for a cosine:

cos x = 
1 - x^2/2! + x^4/4! - x^6/6! + ... =
1 - (x^2/(1*2)) * (1 - x^2/(3*4) + x^4/(3*4*5*6) - ...) =
1 - (x^2/(1*2)) * ( 1 - x^2/(3*4) * (1 - x^2/(5*6) + ...))

etc., which leads to the code

double cos(double x, int n)
{
    int i;
    double rc = 1.0;
    double xs = x*x;

    for(i = n*2; i > 0; i -= 2)
    {
        rc = 1.0 - xs / (i * (i - 1)) * rc;
    }

    return rc;
}
jephthah commented: well, that's clever. thanks for finding that. +7
jonsca commented: Well done +4
nezachem 616 Practically a Posting Shark

The code has two obvious problems. First, its time complexity is at best quadratic. Second, the randomness is not guaranteed.
Given that there are linear algorithms with a true random results (see, for example, shuffling), I don't think that this code has any value.

nezachem 616 Practically a Posting Shark

You can't make the return value of that function anything other than an integer. Why? Because they are not normal functions -- it acts more like a self-contained process than another function, except that threads have access to all global data in the entire program. So when a thread returns it just goes back to the operating system much like any other program would do.

Wrong. The thread process is prototyped to return void * with a purpose. You may return anything it wants. The calling thread may collect the returned value via pthread_join() .

In the following code I am calling a function from a pthread:

pthread_create(&threads[t], NULL, dnssearch, (void *)buffer)

I need to pass the string (buffer) to a function and the have the function pass a string back. What am I doing wrong in the function:

Quite a lot. Starting from a possible buffer overflow in fscanf, and invoking undefined behaviour at line 25, to begin with. Dangerously aliasing an argument. Probably not joining the thread.
Also, it is very unclear what the function is supposed to do; its expected result and actual behaviour. Can you explain it in plain English (especially the do loop at lines 15 to 27)?

Ancient Dragon commented: Glad to know that. Not the first time I've been wrong about something :) +28
nezachem 616 Practically a Posting Shark

The heap got corrupted somewhere else.
Looks like you are using arrays. Make sure there's no overruns, or any other writes beyond the allocated memory, or double deletes, etc, etc, etc. After you find the problem, dump arrays altogether and rewrite everything with vectors.

Salem commented: Well said +20
nezachem 616 Practically a Posting Shark

.data, .bss, etc have nothing to do with the architecture. They represent the structure of an object file. They are linked differently; they are stored differently, they are loaded differently.

nezachem 616 Practically a Posting Shark

I want to know how my local static variable is in .data segment and my global static is in .bss specifically?
One of them ends up in .data, because it is initialized. Another one ends up in .bss because it is not (or, rather, initialized by 0).

and what about that peculiar .1784 naming in that local static variable...
This is how your compiler decided to mangle its name to take it out of the global scope.

nezachem 616 Practically a Posting Shark

Hi, i'm trying to learn some assembly, ive got a assignment from school to control a lcd screen. I've got some sample code that i mostly understand but i can't figure out what the SBI command does.
Using atmega32, with avr studio 4

sbi	PortD, LCD_E

At this point PortD = 32, and LCD_E = 0 (decimal)
After the sbi line PortD = 36

I don't see how he changes from 32 to 36.

.equ	LCD_E	= 2

Do you see now?

Salem commented: Very nice - +20
nezachem 616 Practically a Posting Shark

I wasn't implying full binary search, just a partial binary search.

The problem with even a partial binary search is that if the very first comparison fails (that is, a first marble breaks at the drop from N/2), you need to test the N/2 storeys with a single marble. This gives the worst case of N/2.

PS: You had a slightly different interpretation of the problem. You allow comparison to continue after 2 failures. This is essentially a 3 marble puzzle - which is interesting by itself.
So, having just 1 marble, the problem takes O(N) drops; with 2 marbles it is O(sqrt(N)). What is the asymptotic for 3 marbles? for k marbles?

nezachem 616 Practically a Posting Shark

So here is the algorithm I am trying to design...i'm not sure it will make any sense.
I have a sequence of n numbers(in ascending order). I have an another number 'x'. If i have 2 chances to compare x with a number greater than it but unlimited chances to compare with numbers lesser than it. Now I have to to find out the maximum possible value in the sequence that is less than x in the most efficient way. I know this looks a little contrived but the original question is different so I am looking for the direction I would need to go.

As an example..watch this..

I have a series from 1,2,3,4...............,19, 20.

Now I have a number x = 10.5

Now I have to find the maximum possible number "M" in the series such that M < x

The easiest way would be brute forcing ur way from the lowest possible number(they are in ascending order anyway.). As soon as the "less than comparison" fails, u have the solution. The worst case would 'n' comparisons. But we have two chances where we can fail the comparison. So a slightly better algorithm would be comparing the odd indexed numbers. So in the worst case scenario we have n/2 +1 comparisons which is better than the first.

So far so good. But you still underuse the second chance. Say, you work your way up with an increment of K. The worst case will give you (N/K) + …

nezachem 616 Practically a Posting Shark

I guess i was just trying to see if someone could pose a rational explanation of why I shouldnt do it with gotos, and give an elegant alternative.

That would be extremely hard. Any rationale against goto stems this way or other from the original Dijkstra article. The point of the article is very valid, yet not applicable to this case. Your approach does not violate the sequentiality of the flow, period.

jephthah commented: well-put. i can live with that :) +7
nezachem 616 Practically a Posting Shark

yeah, i try not to jump between functions, this is just to get out of any single function cleanly in the case of a hardware error.

i guess im just soliciting opinions between doing it the first way (with gotos) or the second (without). or another way i havent considered. i'd rather not use gotos because of the stigma attached to them, but i'm not seeing a cleaner way at the moment.

I don't see anything wrong with gotos here. If you are forced to not use them, then in this particular case you can split the functionality into a worker function and a setup-cleanup wrapper, something along the lines of

int MyDriver_workerFunction(int whatever, char * something)
{
   int errCode = ERROR_CLEAR;   // zero (0) is no error
      if ((errCode = subfunction(val1, val2)) < 0) 
        return errCode;
      // ...
   
      for (port = 0; port < MAX_NUM_PORTS; port++)
      {
         if ((errCode = anotherfunction(port, &status)) < 0) 
            return errCode;

         switch(whatever)
            // ...
      }
      if ((errCode = somethingElse(command, response, something)) < 0) 
         return errCode;
   //...
    return errCode;
}
 int MyDriver_driverFunction(int whatever, char * something)
{
   errCode = MyDriver_workerFunction(whatever, something);
   if (errCode < 0)
      // hardware error-specific exit routines ...
   else 
      // standard exit routines ...

   return errCode;
}
nezachem 616 Practically a Posting Shark

I'm trying to write my own system calls. I have a .c file where I'm putting the system calls. My system calls use a struct, so I have declared a global variable that is an array of my struct. Lets just call it

//Stuff is the name of the struct I declared.
Stuff myStuff[100];

I have a function inside of my .c file called "init_Stuff". In order for the stuct to behave properly when a system call it made, init_Stuff must be called one time before any of the system calls will work. From within one of my system calls, I could just say "if the structs aren't initialized yet, go initialize them". But I'm wondering if there is a more elegant/normal way to just call init_Stuff right away. I also have a Makefile that currently just creates an object file of my .c file.

Declare (and define) it with the __init qualifier:

#include <linux/init.h>
void __init init_Stuff();

and call it from linux/init/main.c:start_kernel()

BestJewSinceJC commented: Thanks again +5
nezachem 616 Practically a Posting Shark

Did you look at this?

Kanoisa commented: Nice link thanks, really helped me out +5
nezachem 616 Practically a Posting Shark

Error code 2 is ERROR_FILE_NOT_FOUND. If the path you entered contains spaces, the statement

cin >> way[50];

will only read the first "word" of the path. Use getline().

nezachem 616 Practically a Posting Shark

The postincrement is defined to return int . The preincrement is defined to return int& . In other words, y++ yields an lvalue, and ++y does not. That is, the result of y++ cannot be referenced. It can be const referenced however.

void foo(int & x);
void bar(const int & x);
void baz(int x)
{
	foo(x++);
	bar(x++);
}

testing.cpp(5) : error C2664: 'foo' : cannot convert parameter 1 from 'int' to 'int &'
testing - 1 error(s), 0 warning(s)

As you can see, no complaints on bar .

PS: All speculations based on the exact moment when the value of y changes are wrong. Remember, the function call is a sequence point. It means that when the call happens, all side effects are already completed - no matter which form of the increment is used.

PPS:
The rationale on this difference between pre and post forms of increment is approximately following:
Results of some expressions, such as a = b , ++i , x += y are bound to a variable. Loosely speaking, they have their respective addresses. Results of some other expressions, such as a + b , i++ , etc are not bound to anything. They just exist. There's no address which may refer to them.

nezachem 616 Practically a Posting Shark

First of all,

(f1(x1)*sin(x1)+f2(x1,y1)*(cos(x1)-3*sin(x1)))/3*sin(x1)*(cos(y1)+cos(x1)*cos(y1))

is
((f1(x1)*sin(x1)+f2(x1,y1)*(cos(x1)-3*sin(x1)))/3)*sin(x1)*(cos(y1)+cos(x1)*cos(y1))
I don't think it is your intention.

Second, even assuming correct parenthesis placement, I can't see how you came up with this. I am getting something very different. Again, if you show step by step your math, that would clarify things a lot.

On a side note, I'd recommend to keep the algorithm related code as generic as possible. What I mean is that you factored functions out of the algorithm, yet hardcoded derivatives. Try to implement the algorithm in terms of functions and derivatives, and have derivatives calculated in separate routines. You will see how much more clean and manageable the code will become.

nezachem 616 Practically a Posting Shark

Where did you get this? You must be an archaeologist. The code truly belongs to the past millenium.

The error comes from make, which tries to call lint. Lint is morally obsolete tool (again from seventies), which purpose was to validate the program syntax in such details the old compilers didn't bother to check. You have two choices. Either edit a makefile to remove the lint invocation, or do another digging session to find and install lint.

Ancient Dragon commented: Haven't used lint for over 25 years :) +27
mitrmkar commented: LOL +5
nezachem 616 Practically a Posting Shark

Thou shalt not while(!myfile.eof()) .

Since Dave Sinkula is silent, let me take on this:

while(!myfile.eof())
        {
                        myfile >> circle1 >> op >> circle2;
                        do_something();
        }

Consider the last good iteration. It consumed all the bytes from myfile, but didn't try to read beyond its limits. The end of file hasn't been seen; eof condition has not been set. The loop enters the next round. Of course, the very first read now hits end of file, and whatever you attempt to read is garbage.

nezachem 616 Practically a Posting Shark

First of all, congratulations. Yacc can recover from shift-reduce, whereas reduce-reduce is lethal.

Now, let's look why it happens. One of the sources of the conflict is

Expression		:	Expression PLUSOP Expression

Consider an expression a + b + c. There are 2 ways to parse it:
1. a + Expression
2. Expression + c
The first path would be shift (accept a as Term, and shift to the rest. The second path is reduce (accept a+b, and reduce it to Expression). Again, you didn't tell it which is correct.

There are 2 ways to overcome such shift-reduces. First, you can use %left and %right directives. Second, introduce more non-terminals, like I did with AdditiveExpression.

Reading my original code, it appears, to me, that if a '(' is seen at any time, then the parser needs to have the sub-tree begin with the top-level non-terminal.

It may even do so. The question, unanswered, is what to do when a ')' is encountered.

PS: You are going to have misterious problems with lines 16 and 19. Better start using %union right away.

nezachem 616 Practically a Posting Shark

Writing (line 25) is almost OK (I think that a "+1" was added in an act of desperation, it is not needed there).
Reading (line 30) is a problem. First, a readbuffer is not initialized, so the segfault is imminent. Second, you only reading 4 bytes of the message. Fix those and we can proceed further.

To answer your original question, yes you can. You just need to be careful.

Salem commented: Nice +19
nezachem 616 Practically a Posting Shark

You think wrong. As a function argument, numbers is a pointer. Try to print N_cp.

nezachem 616 Practically a Posting Shark

(Also note that the little face in the original example are created automatically by the blog software when I type colon colon asterisk (to indicate data pointer such as : ::*)

You may consider using code tags, such as ::* . In fact, it is a requirement for this forum.

nezachem 616 Practically a Posting Shark
double *ptr;
spe_in_mbox_ write(thread_args[i].spe_context,(uint32_t*)&ptr,SPE_MBOX...)

its that second parameter thats bugging me giving me a bus error.


Thanks

It would be immensely helpful to see an actual code and an actual error message. For now I see a missing count argument.