0

I am getting segmentation fault in the following code

static char * result;

char s[31];

int i;

random_string(s, 10);



 // for (i = 0; i < 15; i++){
 //     result[i] = s[i];
 // }

strcpy(result, s);

printf("el result es %s\n", result);

where the function random_string is:

void random_string(char * string, int length)
 {
  /* Seed number for rand() */

 int i;

for (i = 0; i < length -1; ++i){

    string[i] = rand() % 90 + 65;
 }

 string[length] = '\0';
}

For some reason I am getting segmentation fault when using strcpy. Also copying byte by byte is not working. What is the problem? I am out of ideas.

DaBler
  • 2,695
  • 2
  • 26
  • 46
Alessandroempire
  • 1,640
  • 4
  • 31
  • 54
  • You should allocate the memory for the array... Look up malloc... – ppeterka Mar 14 '13 at 12:21
  • This very same beginner bug question has been asked 2 times earlier this hour only. Kindly put some minimum effort into researching before posting questions. – Lundin Mar 14 '13 at 12:34

6 Answers6

4

The problem is that result has not been initialized. It results in undefined behavior. Before it can be used like that, you need to make sure it points to a valid buffer. For example:

result = malloc( strlen( s ) + 1 );
Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
2

You forgot to allocate memory to "result" pointer. Try next:

result = malloc( strlen( s ) + 1 );
strcpy(result, s);
Dmitry Sazonov
  • 8,801
  • 1
  • 35
  • 61
2

static char * result; is just an address without any allocated memory!

Try this: [EDITED]

char * result = (char*)malloc(strlen(s) + 1);
Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92
  • yeah that was it. Thanks. And yeah I will accept your answer as soon as it lets me :) – Alessandroempire Mar 14 '13 at 12:26
  • 5
    This code snippet is kind of scary, of course you can't call `strlen(s)` before writing to `s`. I assume that the OP's code is implied to go between the two lines, somehow. – unwind Mar 14 '13 at 12:27
  • Please do NOT cast malloc return value - it can hide certain subtle errors. – paxdiablo Jun 14 '16 at 08:43
0

result is just a uninitialised pointer. You must assign result to a character buffer before using strcpy.

suspectus
  • 16,548
  • 8
  • 49
  • 57
0

You need to assign a valid memory region to your result pointer using malloc or using static memory, as you are doing with your s string. Otherwise your pointer has just a random location assigned and your program receives a segfault by accessing it as it lies out of the boundaries of your program.

nemo
  • 55,207
  • 13
  • 135
  • 135
0

Declare result as a char array like static char result[10];

or assign some memory to result pointer.

µtex
  • 900
  • 5
  • 12