Reputation: 1
I'm working with dynamic memory in C. I'm writing a small function which should
My program gives a segmentation fault.
char *new_line(char *line) {
char *temp_line;
int line_len = strlen(line)+1;
temp_line = malloc(line_len * sizeof(char));
printf(temp_line);
strncpy(temp_line,line,line_len);
return temp_line;
}
According to GDB, my program fails on this function, because apparently it is trying to do something (?) to the address 0x0. This is what GDB says:
#0 0x00007ffff7b7c3c1 in __strlen_sse2_pminub () from /lib64/libc.so.6
#1 0x00000000004008fc in new_line (line=0x0) at myfile.c:35
Can anyone offer some insight on why malloc seems to be returning or messing with 0x0, based on my function? I can't see it.
Upvotes: 0
Views: 2563
Reputation: 1957
There are following issues.
strncpy()
will not put '\0'
at the end. You need to put it explicitly. Since, in this case you have allocated memory by checking size of input string, you can call strcpy()
.
char *new_line(char *line) { char *temp_line = 0; if(0 == line) { printf("Input is null\n"); return 0 } int line_len = strlen(line)+1; temp_line = malloc(line_len * sizeof(char)); if(0 == temp_line) { printf("Failed to allocate memory for new string\n"); return 0; } strncpy(temp_line,line,line_len); temp_line[line_len-1] = '\0'; /* You can replace above two lines with strcpy(). */ printf("Inp string[%s] new string[%s]\n", line, temp_line); return temp_line; }
Upvotes: 1
Reputation: 361869
#0 0x00007ffff7b7c3c1 in __strlen_sse2_pminub () from /lib64/libc.so.6
It's strlen
that's crashing, not malloc
.
#1 0x00000000004008fc in new_line (line=0x0) at myfile.c:35
Notice it says line=0x0
. That means line
is NULL. The code that calls new_line
is passing a null pointer.
int line_len = strlen(line)+1;
Which in turn causes strlen
to be given a null pointer.
Upvotes: 2
Reputation: 33621
printf
uses strlen
internally.
You're calling printf
on a buffer from malloc
that has [possibly] random characters in it [it does not initialize the bytes]. So, strlen
may just "keep going".
Move the printf
after the strncpy
Upvotes: 1