I have a function returning char**
i.e. pointer to array of characters. Here I am reading a file in number of directories for a specific integer value ind
. If it finds the value in the file, it should return the name of the directory. I tried using static allocation but it wont help because returning those variables results in undefined behaviour. In my case I get the all the values same as the last directory name. This probably happens because I am reading from the allocated system stack. I then used dynamic allocation and Here is the code I have written:
//Global variable
int found = 0;
char** get_strings(int ind)
{
FILE *fp;
char filename[64];
char name[16];
//char *name;
char **array;
int i = 0, found = 0, l = 0;
int val = 0;
char **array = (char **)malloc(10 * sizeof(char *));
for(l = 0; l < 10; l++)
array[l] = (char *)malloc(16 * sizeof(char));
//name = (char *)malloc(16 * sizeof(char));
for(i=1;i<=10;i++)
{
snprintf(filename, sizeof(char) * 64, "/home/ben/dir%d/name", i);
fp = fopen(filename, "r");
if(fp == NULL)
{
perror("Error opening file");
}
fscanf(fp, "%d", &val);
fclose(fp);
//printf("value-%d is %d\n", i, val);
if (val != 0 && val == ind)
{
snprintf(name, sizeof(char) * 16, "dir%d", i);
printf("Dir %s is a has %d\n", name, ind);
strncpy(array[found],name, strlen(name));
found++;
}
}
return array;
}
and I am calling it in main function as:
int i = 0;
char **array;
array = get_strings(1);
for(i=0;i< found;i++)
printf("array[%d] = %s\n", i, array[i]);
I get garbage value in the output. Can somebody help?
I think maybe you should not be using strncpy(). Use strcpy(). Try it... also, allocate + 1 in the malloc.
Reason: memory allocated by malloc is not pre-initialized to all zeros. So, your strings there are probably not terminated properly and it will overflow when you call printf. The extra +1 I recommend is simply to store the null byte that is needed in addition to the 16 actual chars you want to store.
Also, for(i=1;i<=10;i++) is wrong. loop from 0 to < 10, and then in your snprintf, use i + 1.
EDIT: by the way, there's a function strdup() which will allocate a string. To use it, i would recommend:
1/ allocate your array with:
char **array = calloc(10, sizeof(char *));
this will pre-initialize all the members to NULL so you won't need to pre-allocate the strings OR put NULL in the slots. Which makes it ready for:
2/ copy the strings in with strdup() if you want to store them:
if(conditions are ripe)
array[found++] = strdup(name);
So now, your loops will go from 0 to < found. If you choose to de-allocate the array of arrays, only call free() on the slots from 0 to < found.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다