• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 305
  • Last Modified:

C Radnom String

Ok, I need to generate some random lowercase strings with C. Here's what I've got so far, and I keep getting Seg Faults.

#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MIN_SIZE 5;
#define MAX_SIZE 20;

char * randstring()
{
  char c;
  char * output;
  int num, i, loop;
  double offset;
  srand((unsigned)time(NULL));
  offset = MAX_SIZE - MIN_SIZE;
  loop = MIN_SIZE+(int)(offset*rand()/(RAND_MAX+1.0));
  for (i = 0;i <= loop;i++) {
    num = 1+(int)(26.0*rand()/(RAND_MAX+1.0));
    num += 96;
    c = (char *)num;
    strcat(output, c);
  }

  return output;
}

Any idea what I'm doing wrong?
0
quirgle
Asked:
quirgle
  • 2
  • 2
  • 2
1 Solution
 
quirgleAuthor Commented:
Oh, I should mention, it seems to seg fault on the stncat function.
0
 
DexstarCommented:
@quirgle:

> Any idea what I'm doing wrong?

You aren't allocating any memory.  Add these lines after the "loop = MIN_SIZE+..." line:
     output = new char[loop + 1];
     output[0] = (char)0;

Hope That Helps,
Dex*
0
 
brunomsilvaCommented:
before the for loop, type this:

output = (char*) malloc(loop);
strcpy(output,"");

and to add the character to the string i advise using sprintf instead of strcat as strcat is designed for strings:

sprintf(output,"%s%c", output, c);

bye,
  bruno
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
quirgleAuthor Commented:
Thanx a lot bruno, works great. I still have much to learn in the C world.

Dex, it didn't understand 'new' char...   Isn't that C++?
0
 
DexstarCommented:
Oops.  I forgot that new was C++.  In, C you should use malloc.

Brunomsilva's answer isn't 100% right though.   It should be:
     output = (char*) malloc(loop+1);
     output[0] = (char)0;

(His strcpy will work too, I guess).

Dex*
0
 
brunomsilvaCommented:
dex,

you are right, i needed an extra byte to store the \0. i forgot that.

cheers,
  bruno
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now