gcc C ***stack smashing detected*** array

4k views Asked by At

The line of code causing the problem is

char command_tb_temp[][1000]={"gcc -Wall ","-o3 -ftree-ccp -fno-align-jumps "," Scripts/*.c -o output -lm && time -f \"%e\" -o TB.log ./output 1.dat"};

When the same code is written by giving only 1 optimizing option like below, It does not return any errors.

char command_tb_temp[][1000]={"gcc -Wall ","-o3 -ftree-ccp "," Scripts/*.c -o output -lm && time -f \"%e\" -o TB.log ./output 1.dat"};

Please help me resolve this issue. Any help is highly appreciated. Thankyou.

Heres the whole function..

int findtb(int flag)
{   
printf("debug -1-1-1");
char command_tb_temp[][1000]={"gcc -Wall ","-o3 -ftree-ccp -fno-align-jumps "," Scripts/*.c -o output -lm && time -f \"%e\" -o TB.log ./output 1.dat"};

char command_tb[]="",line[100];

if(var[initial].exetime>0.00&&flag==1)
{   
    if(var[initial].rip<0.00)
        strcat(finalop,var[initial].name);
    else
        return 0;
}

strcpy(command_tb_temp[1],finalop);
//strcat(command_tb_temp[1]," -ftree-ccp ");        
for(int i=0;i<3;i++)
    strcat(command_tb,command_tb_temp[i]);  
printf("***** %s ****",command_tb);

system(command_tb);     
fp=fopen("TB.log","r");
fscanf(fp,"%s",line);   
tb=atof(line);
printf("\nTb=%f\n",tb); 
fclose(fp);
return 1;

}

The error is...

*** stack smashing detected ***: ./3 terminated
1

There are 1 answers

2
ugoren On BEST ANSWER

char command_tb[] = "" defines a character array of size 1, containing just a terminating null character.
strcat(command_tb,command_tb_temp[i]); then writes data to it.
But it writes more data than it can hold, thus corrupting other parts of memory.

You should make it large enough.

Also, it's advisable not to use strcat, strcpy, as they can easily exceed the buffer. Better use strncpy at others, which get the buffer size and won't write more. It's still your responsibility to provide the right size.
But beware of strncat - the meaning of its size parameter is misleading, so read its documentation with care, or just avoid using it.