c语言显示Runtime Error:Segmentation faul


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main(){
    int t;
    int n;
    int m;
    int i;
    char c;
    
    int c1;
    int c2;
    char *q[20];
    scanf("%d",&t);
    q[0]=(char*)malloc(500);
    while(t--){
        scanf("%d %d",&n,&m);
        getchar();
        for(i=0;i<n;i++){
            if(i!=0)
            q[i]=(char*)malloc(100);
            if(q[i]==NULL)
                printf("gggg");
            gets(q[i]);
            
            }
        for(i=1;i<=m;i++){
            if(i!=1)
            getchar();
            scanf("%c %d %d",&c,&c1,&c2);
                   
                if(c=='A'){
                    
                strcat(q[c1-1],q[c2-1]);
                
                
                }
            if(c=='C'){
               strcpy(q[c1-1],q[c2-1]);
                
                
                }
            
        }
            printf("%s",q[0]);
            for(i=0;i<n;i++){
                strcpy(q[i],NULL);
                }
    }
    for(i=0;i<n;i++){
                free(q[i]);
                q[i]=NULL;

                }
    }

```oj显示Runtime Error:Segmentation faul为什么
```c


问题一:
t>=2的 时候 ,malloc了两次,但是第一次的内存没有被释放;有内存泄露

问题二:
strcpy、strcat是不安全的函数,可能造成内存溢出,使用strncat、strncpy。
例如,strcat(q[c1-1],q[c2-1]);
q[c1-1]长度 99 q[c2-1]长度99
级联之后 99*2 >100,内存溢出

仅供参考,不一定对:


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#include<assert.h>
int main() {
    int t;
    int n;
    int m;
    int i;
    char c;
    int c1;
    int c2;
    char *q[20];
    char s[2];

    scanf("%d",&t);
    assert(t>0);
    q[0]=(char*)malloc(500);
    assert(q[0]);
    while(t--) {
        scanf("%d%d",&n,&m);
        assert(n>0);
        assert(m>0);
        for(i=0;i<n;i++) {
            if(i!=0) q[i]=(char*)malloc(100);
            assert(q[i]==NULL);
            gets(q[i]);
        }
        for(i=1;i<=m;i++) {
            scanf("%1s%d%d",s,&c1,&c2);
            c=s[0];
            assert(1<=c1 && c1<n);
            assert(1<=c2 && c2<n);
            if(c=='A') strcat(q[c1-1],q[c2-1]);
            if(c=='C') strcpy(q[c1-1],q[c2-1]);
        }
        printf("%s",q[0]);
        for(i=0;i<n;i++) {
            strcpy(q[i],NULL);
        }
    }
    for(i=0;i<n;i++) {
        free(q[i]);
        q[i]=NULL;
    }
    return 0;
}


有用麻烦您采纳一下,谢谢