PDA

View Full Version : [C] Help!? Inexplicable Segmentation Fault or Bus Error


eViLegion
10-20-2005, 01:31 PM
Hi, and thanks for reading...

I'm fairly new to this C programming m'larky, and I'm having trouble with the following piece of code. It has to read a long integer (str_length) from the standard input, followed by a string of practically any size, and then copy the first str_length characters that of that string to the standard output.

So far, what I've come up with does appear to do what its meant to... the output gets printed exactly as expected, yet sometime before it manages to execute the "return(0)" statement, the program errors with either a "Segmentation Fault" or "Bus Error".

I just don't see how this is happening? I'd be exceptionally grateful if anyone could give me some idea!

Thanks,
- Tom

--------------------------------------------------------------------------
#include <stdio.h>
#include <string.h>

int main()
{
char* input_str;
char* output_str;
int str_length;

// Scan for the integer
scanf("%d", &str_length);

// Scan for the input string
scanf("%s", input_str);

// Allocate the space for the output
output_str = (char*) malloc(str_length + 1);

// Copy the first str_length bytes
strncpy(output_str, input_str, str_length);

// And terminate the output string
output_str[str_length] = '\0';

// Print the output string
printf("\n%s", output_str);

return(0);
}

aman
10-20-2005, 04:24 PM
I'm suprised it even runs at all.

You haven't allocated any memory to input_str and ...

scanf("%s", input_str);

should crash your program.

nikkiH
10-20-2005, 04:26 PM
Use C or use C++. Pick one. ;)
(comment style)

You never malloc'ed the input.

Compiled and executed with success.

#include <stdio.h>
#include <string.h>

int main()
{
char* input_str;
char* output_str;
int str_length;

/* Scan for the integer */
scanf("%d", &str_length);
input_str = (char*) malloc((size_t)sizeof(str_length+1));

/* Scan for the input string */
scanf("%s", input_str);

/* Allocate the space for the output */
output_str = (char*) malloc((size_t)sizeof(input_str+1));

/* Copy the first str_length bytes */
strncpy(output_str, input_str, str_length);

/* And terminate the output string */
output_str[str_length] = '\0';

/* Print the output string */
printf("\n%s", output_str);

return(0);
}

_Aerospace_Eng_
10-20-2005, 04:31 PM
Use C or use C++. Pick one. ;)
(comment style)
The // will still work as a comment in C.

eViLegion
10-20-2005, 08:37 PM
Thank you ever so much for all the help guys!!!

Hopefully I'll be able to test it out tomorrow!

Thanks again!
- Tom

=D

nikkiH
10-20-2005, 09:36 PM
The // will still work as a comment in C.

Depends on the compiler.
Mine doesn't allow it.

eViLegion
10-24-2005, 12:51 PM
Incidentally... did I mention how much I love you guys for this!?

=D