Function returning pointer to string

Ben Williams

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?

user1646075

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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Pointer to function returning function pointer

분류에서Dev

Returning a pointer to a structure from function

분류에서Dev

Function returning pointer called twice from main()

분류에서Dev

Returning array in Javascript function after splitting string

분류에서Dev

What is the difference between returning a pointer to a calloced int and returning the address of a initialized int in a function?

분류에서Dev

TCL library returning a string from c++ function

분류에서Dev

UUID returning null pointer exception

분류에서Dev

PHP function not returning value

분류에서Dev

Returning managed pointer from a clone method

분류에서Dev

Pointer returning NULL from extern structure in C

분류에서Dev

Returning a pointer to a struct using dynamic memory allocation

분류에서Dev

Returning string is not successful

분류에서Dev

Function to Return Node Pointer

분류에서Dev

Pointer to array of struct in function

분류에서Dev

Pointer to function (list)

분류에서Dev

Passing a pointer to a function

분류에서Dev

Returning a value from a recursive function

분류에서Dev

double function only returning -0

분류에서Dev

Function not returning the Value of its Key

분류에서Dev

NSArray Returning String Instead of Dictionary

분류에서Dev

jquery function not returning html to second function

분류에서Dev

Change address of kernel function pointer

분류에서Dev

when to pass a pointer argument to a function

분류에서Dev

When to use "this" pointer in member function

분류에서Dev

Trying to Convert String to Character Pointer?

분류에서Dev

Assign pointer type to string type

분류에서Dev

Ambiguous overload on function pointer and std::function

분류에서Dev

Wrap c++ function that needs function pointer

분류에서Dev

called object is not a function or function pointer in use of ternary

Related 관련 기사

뜨겁다태그

보관