Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault- strcat

This is my code:

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

void main(int arge, char *argv[])
{
    FILE *f1;
    char ch,*fn="~/lyrics/";
    strcat(fn,argv[1]);
    strcat(fn,".txt");
    if( (f1 = fopen(fn,"r"))==NULL )
    {
        printf("\nWrong filename\n%s not found",argv[1]);
        return;
    }
    while((ch=getw(f1))!=EOF)
    {
        printf("%c",ch);
    }
}

I compiled it using gcc -g -o file file.c and the compiler gave no error messages. But when I run it I get the error message:

Segmentation fault (core dumped)
Bad permissions for mapped region at address 0x8048659 at 0x402C36B: strcat 
(in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) by 0x80484D6: main (lyrics.c:9)

Can anyone please help me?

like image 620
Mahesh Bansod Avatar asked Dec 16 '12 12:12

Mahesh Bansod


People also ask

Is Sigsegv an exception?

On Unix-like operating systems, a signal called SIGSEGV (abbreviated from segmentation violation) is sent to the offending process. On Microsoft Windows, the offending process receives a STATUS_ACCESS_VIOLATION exception.


1 Answers

You don't have enough space in fn. By strcat'ing on to it you overwrite the end of its stack allocation and into the stack .. hence the segmentation fault.

You could try the following instead:

char fn[255];
strcpy( fn, "~/lyrics/" );
strcat( fn, argv[1] );
strcat( fn, ".txt" );

You just have to be sure that the whole path and filename can fit into 255 characters.

Alternatively you could do this:

char* fn = NULL;
int argvLen = strlen( argv[1] );
fn = malloc( 9 + argvLen + 4 + 1 ); // Add 1 for null terminator.
strcpy( fn, "~/lyrics/" );
strcat( fn, argv[1] );
strcat( fn, ".txt" );

And you have definitely allocated enough space for the string. Just don't forget to free it when you have finished with it!

like image 175
Goz Avatar answered Sep 20 '22 01:09

Goz