Why do i get a crash on strcpy
even. I tried appending a 0,\0,\n using sprintf and check in gdb that its appended correctly but still i get a crash.
With malloc i dont get a crash, but somebody told me that malloc is not necessary in this case.
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;
}
The problem is in this statement strcpy(str[strCount],line)
char *str[100];
declares an array of 100 uninitialized pointers whereby each pointer needs to be allocated memory explicitly.
When you run str[strCount]=malloc(MAX_LINE_SIZE);
statement, you are actually allocating memory for invidual pointers which is further used by strcpy to copy string.
When you are not using malloc, its an uninitialized pointer (having no allocated memory) causing strcpy to fail as you are coping in memory that may not belong to you or may not exist at all.