deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Here are my downloads and impressions in order of preference so far. The season just started though.

  • Genshiken Nidaime: By far my most anticipated of the new series. I regularly reread the Genshiken manga and fully intend to follow this one to the end.
  • Watashi ga Motenai no wa Dou Kangaetemo Omaera ga Warui: If it's anything like the manga (and judging from the first episode), it should be a fun ride.
  • Kiniro Mosaic: The first episode looks good. I'm hoping that it turns out well, and it's my #3 for this season. However, the first episode was just setup for the environment, so the true test will be the next episode.
  • Blood Lad: It's hard to say at this point, but I didn't skip through the first episode, which is a decent sign.
  • Kitakubu Katsudou Kiroku: This strikes me as another school club random anime, but those aren't bad. Time will tell, but I didn't skip through the first episode at all.
  • Love Lab: Somewhat entertaining, but I did skip at a few points out of boredom. I suspect this will be dropped if it doesn't get better in the next two episodes or so.
  • Servant x Service: I skipped through it at several points, but there's potential, so it'll go through my 3 episode test. Most likely I'll drop it though.
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

n grows by a factor of 4 (16384 / 4096 = 4), right? And the run time also grows by a factor of 4 (2048 / 512 = 4), right?. While it's certainly not a conclusive test, from those two data points you really can't do much more than say it's either O(n) or that the answer requires more information.

o() is big-oh!

That's confusing. There's also a little o, which represents a strict upper bound and uses, intuitively, a lower case o. So o(n) is not the same as O(n) in standard notation.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I didn't like your general attack on realloc.

I suspect you're just miffed that the "attack" was both accurate and happened to be directed at your code. In my experience, bruised egos are one of the more common reasons for stubbornly defending a losing argument.

You're right that the OP is inexperienced and so malloc/free could cause him some problems.

I'm tempted to think the same of you. Once again, your example was a pefect case of how not to use realloc() in C++. Rather than fight to the death for your beloved function, maybe you should sit back and objectively consider what Mike and I have said.

To be fair though, for all you know he doesn't need to use new/delete at all, and could allocate all memory onto the stack.

Given the phrase "dynamic array of rectangles" in the OP, I'd say that's extremely unlikely. Dynamic allocation on the stack, while possible through solutions such as alloca(), generally isn't taught to beginners. Further, it's unconventional enough to justify explictly stating that the allocation is to be both dynamic and on the stack.

Though if you're grasping at something to be right about in this thread, I'll give you that point if it'll make you feel better.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

For example, the A star algorithm performs nearly an order of magnitude faster with realloc.

I'll take your word for it.

I don't see how you can say the functionality of reallocation in place is useless.

It is when you assume that the reallocation is in-place, which is not guaranteed even for realloc().

You are wrong.

False. You are wrong within this thread. For niche applications I'll concede that realloc() has potential unguaranteed performance benefits if used safely. However, that in no way excuses your recommendation that realloc() be used in the general case, or even in the specific case of this thread, especially given that your example of using it was in fact unsafe.

I don't believe you understand the cases in which realloc can and should be used.

What I (and Mike) understand are the limitations of realloc(), which directly apply to how it can and should be used. Your example in this thread was one of the cases where it should not be used, which immediately brings into question your understanding.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm not sure you read my post correctly.

That seems to be the case. You appear to have meant indexing the underlying array whereas I meant a wrapper interface by overloading the subscript operator. I agree with you that making array[area] work (where array is the underlying array) is not a great idea. In fact, I'd flat out call it stupid, given the requirements from the OP. There's no reason at all to organize the underlying array like that. ;)

P.S. I don't like your reason for avoiding malloc; that you assume the programmer is an idiot.

The only time malloc() is guaranteed to be safe is when allocating for a built-in type. The instant classes enter the picture it becomes too risky. To avoid having to remember what types are safe and what types aren't, best practice is to forget that malloc() exists. You have two options in standard C++ that eliminate a need for malloc() entirely:

  1. new/new[] and delete/delete[]. These will properly allocate memory and handle the calling of constructors and destructors for all types.

  2. std::allocator and derivatives. These give you more control such that you can allocate and release raw memory but also have a clean interface for calling constructors and destructors for all types. The intended use is in the implementation of things like collection classes, but there's nothing stopping you from using an allocator for any dynamic allocation.

There are plenty of valid cases both for and against malloc …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Whew, a lot of questions. ;) I'll answer them, but before doing that I'll strongly recommend that you consider memory mapping your files if you go the route of file lists. That way you only need to manage the organization of the files themselves as well as the memory maps, and after that your code can just pretend to be working with really large arrays. So the meat of your code that exists now won't need to be modified much, if at all.

My first question then is: is it okay to keep the file open and still use it as large storage?

Yes, but keep in mind that there's a limit to the number of files you can have open at one time. Usually both a system and a stream library limit will be imposed and they may or may not match. In the C stdio library, the limit is defined in the FOPEN_MAX macro.

is there any way to NOT have to re-open those files every time I need them?

You need some sort of way to access the files, whether it be keeping them open or re-opening them.

is there any way to get the file name out of a FILE structure in stdio.

Not portably, no. You'll need to maintain a map of the file with its path.

fstream IS an option, except that I definately need speed and as far as I know I can get more of …

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The error is precisely what it says: the file cannot be deleted until all processes have closed it and disposed of any references to it.

I'd suggest downloading and running Process Monitor to find out which process still has a lock on that file. This will give you some direction in how to fix the problem, if the process turns out to be your own. If the process isn't yours, you're SOL and simply need to wait until the file is unlocked.

However, I'm willing to bet that it's your process and that the stream wasn't properly disposed or you didn't give the garbage collector enough time to fully dispose it. First and foremost you need to ensure that any streams or file operations on that file are closed and disposed before trying to delete it. If the problem still occurs, sometimes you need a retry loop as added insurance:

public bool SafeDelete(string path, int retries)
{
    for (i = 0; i < retries; i++)
    {
        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
                return true;
            }
        }
        catch (Exception ex)
        {
            Thread.Sleep(100);

            // Log if desired
        }
    }

    return false;
}
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

i tried to free()mem i allocate in prog using malloc

But you don't. You try to free the result of fun(), which is a pointer to int that corresponds to the address of x in main(). In other words, you're trying to free something that should not be freed. The problem is here:

// Memory is allocated to num, all is well
int *num = (int*)malloc(sizeof(int*));

// The memory allocated above is leaked away and now num points to TX,
// which is a pointer to x in main (*not* a pointer to dynamic memory)
num=(int*)TX;

At this point you already have a memory leak, and any attempt to free num or any reference to num will fail miserably because the pointer was not previously returned by malloc(), calloc(), or realloc().

Remove that second line as it's wholely unnecessary in the first place. What you probably wanted to do is this:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *fun(void *TX)

int main(void)
{
    void *exitstat;
    pthread_t t;
    int x = 50;

    pthread_create(&t, NULL, fun, &x);
    pthread_join(t, &exitstat);

    printf("%d\n", *(int*)exitstat);
    free(exitstat);

    return 0;
}

void *fun(void *TX)
{
    int *num = malloc(sizeof *num);

    *num = *(int*)TX;
    *num += 10;

    return num;
}

Why are you freeing TX?

While correct, that's not informative.

ddanbe commented: Respect! +14
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

P.S. Feel free to use new/delete if you never resize the array, they are faster operations for single allocations.

I'd strongly recommend against using malloc(), calloc(), realloc() (and by extension free()) because they don't respect the presence of constructors and destructors. If you're working with any class type, you're flirting with danger by not using new/delete for explicit dynamic allocation.

If you want to reallocate a block of memory, it's a simple matter to copy and reassign pointers:

if (new_size != old_size)
{
    Rectangle *temp = new Rectangle[new_size];
    size_t n = old_size < new_size ? old_size : new_size;

    copy(temp, temp + n, rectangles);

    delete[] rectangles;
    rectangles = temp;
}

P.P.S Indexing by area seems unwise for a number of reasons, including but not limited to wasted memory.

"Indexing" in this case is nothing more than a search wrapped in a cute little package. It's no different than if you defined it as:

Rectangle *find_by_area(int area);

Though the above would be the better option for a search as it makes clear that a potentially expensive operation is happening.

Do please give an example of how memory is wasted in a search algorithm. And note that since the OP is clearly a beginner, we're looking at probably a simple linear or binary search that uses no extra memory (barring a few variables which are negligible).

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

if a[3][3] is defined and you are given a[0][2] address(32114) and you are asked address of a[1][0] , isn't it 32118 (on 32-bit compiler) ?

Is it probable? Yes. Is it guaranteed? No.

if not, then what should i answer to this question ?

The same answer I've given you several times: there's no guarantee that you can acquire the address of an item in one array from an item in another array, even if those arrays are subdimensions of a 2D array.

There are three solutions:

  1. Recognize that the requirement exhibits a broken design and fix the design.
  2. Replace the 2D array with a manually allocated block of memory that's guaranteed to be contiguous:

    #include <stdio.h>
    #include <stdlib.h>
    
    #define N 3
    #define M 3
    
    int main(void)
    {
        int *base = malloc(N * M * sizeof *base);
    
        if (base) {
            int **matrix = malloc(N * sizeof *matrix);
            int *p;
            int i;
    
            if (!matrix) {
                free(base);
                return EXIT_FAILURE;
            }
    
            for (i = 0; i < N * M; i++) {
                base[i] = i;
            }
    
            for (i = 0; i < N; i++) {
                matrix[i] = &base[i * M];
            }
    
            printf("[0][2] -- %p: %d\n", (void*)&matrix[0][2], matrix[0][2]);
            printf("[1][0] -- %p: %d\n", (void*)&matrix[1][0], matrix[1][0]);
    
            p = &matrix[0][2];
    
            printf("%p: %d\n", (void*)p, *p);
            ++p;
            printf("%p: %d\n", (void*)p, *p);
    
            free(matrix);
            free(base);
        }
    
        return 0;
    }
    
  3. Simply increment your pointer and hope for the best. It'll probably work, but such things tend not to work at the most inopportune times.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

but still can you tell me the way in which it is mostly implemented ?

rand() is usually implemented with some form of linear congruential generator.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

my job was primarily to solve problems, not to write code

Code is merely a tool. As a consultant my job is to make clients happy by removing obstacles in the way of them getting their jobs done optimally. I just happen to do that with code often because it's a fantastic way of accomplishing that goal. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

what do you think makes a better programmer ?

It depends on the ultimate goal. If the goal is to be a programmer who can win competitions, the answer is clearly a. If the goal is to be a viable programmer in the working world, b is the answer. While you certainly need problem solving and coding skills in both cases, my experience is that competition strategies do not translate well into real world projects and vice versa.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I suspect you meant for Monster to be a class rather than a namespace.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

There are good tutorials out there if you search for them. I started writing a cryptography library a couple of years ago and abandoned it, so all of my supplementary bookmarks and references are gone, unfortunately. However, I can at least offer you a basic implementation. :)

I wrote it using the standard definition, and the test driver uses the test cases from that document. It's as simple as I could make it while maintaining core functionality, but please do keep in mind that this isn't a finished project, just a work in progress. As such the comments are lacking and the design is a first draft.

Here's the test driver:

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include "aes_provider.h"

using namespace encryption;
using namespace std;

#define length(a) (sizeof (a) / sizeof *(a))

void display_bytes(const std::string& message, vector<unsigned char> output)
{
    cout << message;

    for (vector<unsigned char>::size_type i = 0; i < output.size(); i++)
        cout<< setw(3) << hex << left << (unsigned)output[i];

    cout <<'\n';
}

int main()
{
    unsigned char key_init[] = {
        // 128-bit key
        /*
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
        */
        // 192-bit key
        /*
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 
        0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17
        */
        // 256-bit key
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10, 0x11, 0x12, 0x13, …
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Instead of where to put a semi-colon and where not to put the semi colon.

As opposed to where to put a space and where not to put a space? ;) All real programming languages are nitpicky about syntax, just in different ways. Regardless of which language you learn, you have to learn the syntax and apply it correctly.

But syntax is by far the simplest part of any programming language, almost to the point of being irrelevant as a learning curve metric.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Just use a vector internally and copy the array into it as an alternative constructor. Or you could have the underlying collection type be a template argument to the class. Or you could use inheritance from an interface to define both an array-based class and a vector-based class.

But I'd favor using a vector and taking an array initializer in one of the constructors for sheer simplicity of design.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I don't think you're making the connection here. You write the variable's value to a file to store it before the program ends. Then when the program starts back up, you read the value back into a variable. That's all there is to it.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'm having trouble thinking of a programming language that doesn't support reading and writing files. C++ certainly supports it. Click on this link for us professionals' secret database of arcane knowledge.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Given that "how to develop software" is extremely broad, I'll answer the specific question you asked.

how can i make the program to remember the value the user assigned to its variables without erasing it everytime i close the exe file running the program??

Persistant data would be saved to the hard drive or some other semi-permanent storage and then loaded back into memory when the program is run again.

pbj.codez commented: you said it in a fancier fashion then I ever could. nice +2
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It's impossible to say since study time to a working knowledge of programming varies greatly from person to person and "working knowledge" is such a nebulous term. Can you be more specific?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

How would you do it by hand? That's a good first step in defining an algorithm.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

...

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

We can't read you mind.

Nor will we do your work for you. Keep that in mind.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

firstly what was "yeah...no", means partial right , partial wrong ?

Completely wrong. Not even close. ;) Sadly, the "yeah...no" thing doesn't translate to a strictly text medium very well.

but why generality doesn't work at that level ?

Perhaps this tutorial will help.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Yeah...no.

A pointer to void is a generic object pointer, it can point to any object type (but not a function pointer type). For example, the following code has no errors:

void foo(void *p) { }

int main(void)
{
    int *a;
    char *b;
    double *c;

    foo(a);
    foo(b);
    foo(c);

    return 0;
}

int*, char*, and double* are all compatible with void* and can be safely converted to void*. Likewise, in C a void* can be implicitly converted back without a cast. That's why you don't need to cast malloc() even though it returns a pointer to void:

char *p = malloc(10); /* No cast needed! */

The reason I asked about void* and void** is to introduce you to this subtle little error:

void foo(void **p) { }

int main(void)
{
    int **a;

    foo(a);

    return 0;
}

The "genericalness" no longer applies. p is a pointer to a pointer to void, not a pointer to a pointer to some undisclosed object type. Therefore int** is not compatible, and the only type you can pass into foo() is a void**.

The reason I gave you this question is because const has somewhat similar behavior. You can convert int* to const int*, but int** and const int** are incompatible for the same reason as with void* and void**. The added level of indirection is the culprit.

Tumlee commented: Excellent explanation. +5
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Are ProjectConstants::CONSTANT1 and ProjectConstants::CONSTANT2 declared in the global namespace or not?

A using declaration introduces names to the current namespace, so in this case yes, they are indeed in the global namespace for that particular translation unit.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

What is "nothing"?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

The compiler can do it, but you're not guaranteed anything by the C standard to do it yourself. At least not with built-in arrays.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I'll explain by giving you some homework. The answer to the following question will also give you a hint on your current question.

Q: What's the difference between void* and void**?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

then why we study about row major and column order ?

Because matrix theory is important?

then how are we able calculate the adress of a[3][4] given the address of a[0][0] ?

You let the compiler do it: &a[3][4]. If you want to play address games and do everything manually, you need to allocate your own memory to ensure that it's set up the way you want.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Are you compiling as C++?

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

how are arrays stored in memory ?

The compiler can do whatever it wants as long as the resulting behavior is unchanged. That's why it's undefined behavior to treat a 2D array as if it were a 1D array.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I will do your homework for you after you deposit $10,000.00 USD in my PayPal account.

You may want to qualify that, or you could end up doing a college student's "homework" from day one to a PhD thesis. That's not something you want to do for a mere $10k. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Please read our rules concerning homework.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

C# is a Microsoft specific language and relies on the Microsoft compiler, so your options are very limited.

.NET is a Microsoft specific implementation of the CLI that includes C#. C# is an internationally standardized language whose evolution is driven solely by Microsoft presently, but there's nothing stopping someone from writing a compiler for it. If nothing else, the existence of Mono belies your statement that C# relies on the Microsoft compiler.

I'm curious why the OP wants to exclude Visual Studio.

Ketsuekiame commented: Good point about C#, was just trying to simplify. As you say, it's pretty much solely driven by MS. +9
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

And finally, I also share Ancient Dragon's concerns about security.

Likewise. If you look at history, you'll see a distinct pattern of alternating between centralizing and decentralizing when it comes to data storage and retrieval. Right now with the whole Cloud nonsense we're in a decentralization period, but I'd wager that one good sercurity breach will find everyone scrambling to centralize again and secure local software will keep on keeping on. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You're pretty much SOL for built-in array types because all dimensions except the first require a size. In C99 and C11 with VLAs defined you can pass an VLA, but for the most part the recommended solution is a dynamically allocated 2D matrix so that you can pass a pointer to a pointer:

void display(int **a, int m, int n);
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

here point is not about if it is useful or not, but is it perfect ?

By definition unnecessary stuff makes it imperfect.

I mean is there any error or undefined bahviour in this ?

No, it's legal and will produce the desired behavior portably.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

It'll work, but the & operator is completely unnecessary.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can you please explain that how "hello" is working here ?

Luck. :) Technically it's undefined behavior because you're passing an object of the wrong type to printf(). Functionally though, "hello", &"hello", and &("hello"[0]) all evaluate to the same address, so it's not difficult to see why your output is correct.

so, if it is the case, then why do i need & to find it's address ?

You don't, and in fact the code you posted is wrong because of the & operator. The unadorned string literal has the correct type for %s (I'll address %p in a moment). As AD alluded, %u is incorrect for printing addresses because there's no guarantee that unsigned int can represent the value. The %p specifier exists for formatting addresses, but it's often used incorrectly (see below).

printf("%p %s","hello","hello");

Close. The %p specifier requires a pointer to void, but as a variable argument, the pointer you pass isn't automagically converted to void* for you. Internally, printf() will interpret the object you pass as if it were void*, which can blow up in your face on the off chance that the underlying representation of the two pointer types are different. In practice it's not a problem in all implementations I'm familiar with, but technically it's undefined without a cast. This is the correct call to printf():

printf("%p %s\n", (void*)"hello", "hello");
deceptikon 1,790 Code Sniper Team Colleague Featured Poster

Compare this with your code and see if you can figure out why I made certain changes:

for (char *i = beach; *i != '\0'; ++i)
{
    if( *i >= 'a' && *i <= 'z')
        *i -= 'a' - 'A';
}

You've inspired me to do a pony avatar ha ha

Welcome to the herd. :D

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

A character literal uses single quotes, string literals use double quotes. There's a difference, and it's rather significant. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

If you're absolutely sure you're correct, don't be afraid to say so. The worst thing that could happen is someone will irrationally hate you when you surely prove them to be incorrect.

Of course, if you're sure you're correct but you're not, be willing to accept when someone proves you wrong. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

localhost or not, the machine must have a mail server installed and running or SMTP simply won't work.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

statements of you and James sir are little bit contradictory.

Rest assured, I'm correct and AD will realize this eventually. In this particular case, typedef is absolutely required to be strictly correct for complex types. The standard is very clear about it, but it is an edge case.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

int (fn)() = (int (_cdecl *)())va_arg(vl,int);

All I can say to that is ewwww. There's a hyoooge assumption that pointers to functions are equivalent to pointers to int. Very risky, and non-portable at best.

what else i need to typedef like this ?

Pointers to arrays come to mind.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

I see on some other forums, they have a button to mark all as read if you need, and then only the individual threads are marked if you don't use it.

That's available on Daniweb as well, but from the forum list here.

But I'm quite sure that this only started happening a few weeks ago.

The feature has been in place for several years now...

When I don't want the forum read, I simply leave the first post until last, as unintuitive as that is. ;)

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

can you explain why it is so

This is one of those cases where the reason why is "because the standard says so". Seriously, sometimes it's that simple. It probably has to do with difficulty in parsing for the compiler, but the reason why is totally irrelevant for you as the end-developer. It just is, and you have no choice but to comply.

As for other exceptions, the standard explains in adequate detail. If you can't say <type>*, you must use a typedef. End of story.

deceptikon 1,790 Code Sniper Team Colleague Featured Poster

You did miss it. Simple types aren't a problem, but complex types like nitin's example are, Reread the description of the type parameter in your link and it will correspond to my quote from the standard. You're correct that it says nothing about typedef, but keep in mind that int(*)()* is meaningless.