Reputation: 307
In the below code I get a sementation fault BUT whe I add a \n at the end of printf ("* I started to learn C!! \n "); it solves the problem. Any ideas ?
#include <stdio.h>
#include <string.h>
char* draw_line(int line_len, const char style) {
int i;
char *line;
char s_style[2] = {style, '\0'};
strcpy(line, "\n");
for(i=0; i<line_len; i++) {
strcat(line, s_style);
}
printf("%s\n", line); //debug
return line;
}
int main() {
char *line;
printf ("* I started to learn C!! ");
line = draw_line(5, '*');
// printf("%s\n", line);
return 0;
}
Upvotes: 1
Views: 65
Reputation: 62908
At least these lines are a problem (not the middle one, just keeping it there for context):
char *line;
char s_style[2] = {style, '\0'};
strcpy(line, "\n");
Here line
is uninitialized, which means it will have what ever happens to be in the stack in the location where line
is stored. Then this "random" address is taken by strcpy
, which copies that two-byte string there.
If address is in location where you are not allowed to write, you got lucky, your program crashes with segmentation fault, and debugger shows you the problem line in stack trace.
However, if address happens to be for a writable memory location, then whatever is there gets written over. And what happens then, all bets are off. It could be unused memory and nothing happens. It could be some text and you only get corrupted text somewhere, It could be some important variable which will make your program act funny. It could be a return address in stack, causing your program do something totally unexpected when it jumps to corrupted address. Stack can have all kinds of values left there from previous function calls and local variables, so it is quite possible that address even contains value from some other pointer.
But the thing is, when you change the code, in any way, the value left in stack, and the taken by uninitialized variable, can and does change, so any change can make your code behave differently. This is probably what happens when you add the printf
.
Simply put, don't do that. Dereferencing uninitialized variable is Undefined Behavior.
To avoid many bugs like this, enable warnings for your compiler and fix them (for gcc and clang, command line switches -Wall -Wextra
are a good combo for any new code).
Upvotes: 1