tags:

views:

138

answers:

7

I was given task to generate random 80 byte keys and i have decided following strateges

in my computer sizeof(char)=1 so i have created array of english alphabetical letters

char *p=" ";
char a[0..26] and in cycle 


for (int  i=0;i<=80;i++){
   *(p+i)+= a[(rand()+100) % 26];
}

but it does not work it stops execution please help sorry if my code is stupid but i can't think at this time otherwise thanks code

#include <iostream>
#include <string.h>
#include <cstdlib>
using   namespace std;
int main(){

    char *p=" ";
    char  a[]= { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
 for (int i=0;i<=80;i++){
        *(p+i)+=(a[(rand()+100)%26]);
    }

     cout<<p<<endl;


     return 0;

}
+1  A: 

You need to allocate space for the full size of your char array p before writing into it in the loop.


Update By the way, rand() isn't very random if you don't seed it with a unique value first using srand.

Dave Bacher
+1  A: 

You are assigning characters in your p variable but you have not allocated memory to assign those characters. You probably want something like this:

char p[81];

and then go from there.

Starkey
+3  A: 

Well, normally I'd say that you need to provide more information than "it stops executing," but a few things jump out at me:

    char *p=" ";
    char  a[]= { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for (int i=0;i<=80;i++){
         *(p+i)+=(a[(rand()+100)%26]);
    }

Your loop is writing values into *p from index 0 to 80 (81 total elements).

The first iteration iteration:

*(p+0) = a[...]; 

will work, but the second one

*(p+1) = a[...];

should fail since there's no reserved memory at address *(p+1). This may be off by one if you can write to the space reserved for the null \0 that's appended to the string literal.

When you declare *p as

char *p=" ";

You're only allocating 1 byte. So, when your loop writes to p[1], p[2]... you're attempting to write into unallocated memory. Change your declaration to something like

char pArr[81];
char *p=pArr;

and go from there.

David Lively
The syntax of the declaration is correct.
Venza
@Venza thanks. I was getting ready to whip out the C compiler. Easy questions are kind of cathartic.
David Lively
On your last point: p[0] and p[1] do actually point to real memory. However, it's likely read only memory. The fix would work fine though.
sharth
+2  A: 

Try this out:

#include <iostream>
#include <string.h>
#include <cstdlib>
using   namespace std;
int main(){
    // ensure the target has enough memory for the key and a null terminator
    char p[81];

    // this string will do as nicely as the character array
    char a[] = "abcdefghijklmnopqrstuvwxyz";

    // no += here. I assign the random character directly to the target buffer
    for (int i=0;i<=80;i++)
        p[i] = a[rand()%26];

    // alternately, you can calculate a random English character with:
    // p[i] = rand()%26 + 'a';
    // which removes the need for the a[] buffer at all

    // don't forget to null-terminate
    p[80] = '\0'

    // output results
    cout<<p<<endl;
    return 0;
}
kbrimington
Your code looks good, but I'd recommend adding some explanation to your answers in the future (especially for such a basic question as this).
David Lively
@David: Fair enough. I hadn't much more to say than was already said in other responses, except for the note about null termination. I'll make a point to be more descriptive in the future.
kbrimington
What is the +100 for?? To prevent accidents it may be worth making `a` a const. Also since A is an array why make the modules operator use a const. Make it use the size of the array. That way if the array is expanded you don't need to upgrade the algorithm.
Martin York
@kbirmington Didn't mean to be snippy. My answers tend to the opposite end of the spectrum (too verbose).
David Lively
@Martin: The +100 was to imitate the OP's example. Good point about basing the modulus on the length of the array rather than a hard-coded constant. I'll update the code with your suggestion and comments.
kbrimington
Not perfect: The probability for each character is not equal, since RAND_MAX is not a multiple of 26
Lior Kogan
@Lior: They're equal enough. There was no indication in the question that the key must be cryptographically secure.
kbrimington
+1  A: 

I have modified your code...try it out.

#include <iostream>
#include <string.h>
#include <cstdlib>
using namespace std;
int main(){

    char *p= new char[81];
    char  a[]= { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
 for (int i=0;i<=80;i++){
        *(p+i)=(a[(rand()+100)%26]);
    }

     cout<<p<<endl;


     return 0;

}

So what is the output?

MOLi
A memory leak, for starters.
Dennis Zickefoose
+1  A: 

A question about this code:

Why generate an array of alphabetical characters? Why not get a random, modulate by 26, and add the offset to ASCII "a"? This saves a memory allocation, and is, in my mind, more clear.

babbitt
That's a fair question. My guess is that respondents were trying to minimize the amount of new material presented to the (obvious) beginner question. You'll see that 'round these parts; welcome to SO.
msw
Two reasons pop out at me. First is that you aren't guarenteed that `'a' + 1 == 'b'`. The second is that it isn't particularly extendable. What if you need digits, or capital letters? Or both, but without lower-case el, or capital Oh, because they look like numbers? The simplicity of an array based solution more than outweigh the slight overhead of an extra sixty or so bytes of data.
Dennis Zickefoose
Fair enough. Thanks for the insight.
babbitt
A: 

For completeness:

std::vector<char> BuildKey(std::size_t keyLength)
{
    const char elements[] = "abcdefg0123!@_";
    const std::size_t numElements = sizeof(elements) / sizeof(char);
        //division technically superfluous, as sizeof(char) == 1, but in general its needed.

    std::vector<char> key;
    key.reserve(keyLength);
    for(std::size_t i = 0; i < keyLength; ++i) 
        key.push_back(elements[rand()%numElements]);
    //there are a handful of ways using standard algorithms to achieve this,
    //  but I'm largely unconvinced the added complexity is justified for simple loops

    return key;
}

There are a few more changes one could make. I would probably paramaterize out rand so I can choose my PRNG later, and possibly provide the elements array as an input as well. And string might be more appropriate than vector depending on how you plan on using the key. Or just accept a ForwardIterator, and return void. Lots of choices.

Dennis Zickefoose