SIGSEV on strcpy到char指针

时间:2019-06-29 04:40:17

标签: c strcpy

为什么我甚至在strcpy上也崩溃了。我尝试使用sprintf附加0,\ 0,\ n,并在gdb中检查其正确附加,但仍然崩溃。 使用malloc时,我不会崩溃,但是有人告诉我,在这种情况下,不需要malloc。

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

#define MAX_LINE_SIZE 10

int main()
{

        char* str[100];
        int strCount=0;

        char cCmd[] = "<some command>|awk '{print $1}'";
        FILE *fp;
        fp = popen(cCmd,"r");


        if(cCmd != NULL)
        {
                char line[MAX_LINE_SIZE];
                while (fgets(line, sizeof(line), fp) != NULL )
                {
                        //str[strCount]=malloc(MAX_LINE_SIZE);
                        //sprintf(line,"%s%c",line,'\0'); -- even with appending a null character at the end it doesnt work
                        strcpy(str[strCount],line);
                        //strip(str[strCount]);
                        (strCount)++;
                }
        }
        return 0;
}

1 个答案:

答案 0 :(得分:3)

问题出在此语句newtonsoft.json

strcpy(str[strCount],line)声明了一个由100个未初始化指针组成的数组,由此需要为每个指针显式分配内存。

运行char *str[100];语句时,实际上是为单个指针分配内存,strcpy进一步使用这些内存来复制字符串。

当您不使用malloc时,它的未初始化指针(没有分配的内存)会导致strcpy失败,因为您正在处理可能不属于您或根本不存在的内存。