【发布时间】:2019-06-29 04:40:17
【问题描述】:
为什么我会在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;
}
【问题讨论】:
-
@anurag86
str[strCount]指向的指针是什么?嗯....告诉你它不需要malloc的“某人”可能是说“你不需要malloc来管理这里的内存”。只需使用数组数组;不是指针数组。 -
@anurag86 在使用
strcpy将字符串复制到该指针之前,您绝对需要为指针分配内存。在另一个问题中,我们试图告诉您的是,malloc()不是执行此类分配的唯一方法。还有其他方法。 -
True 声明:指针必须指向有效内存才能使用它,例如,在您可以使用
strcpy将字符串“复制”到其中之前。错误陈述:必须使用malloc初始化指针才能使用。 -
真实声明:使用前不需要调用
malloc来初始化指针;还有其他方法。错误陈述:使用前不需要调用malloc来初始化指针;你可以继续使用它而不初始化。 -
@anurag86 请阅读the other question 的所有答案——我不确定你是否从中得到了所有答案。另外,您是否阅读了生成的chat session?