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);
}
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);
}