jjamzn
jjamzn

Reputation: 31

Returning char* to print in C

So I am trying to print out a char * array after being returned from a function but I keep getting a segmentation fault.

char *return(node *n) {
    node *p = list->head;
    int count = 0;
    int size = 0;

    while (p != NULL) {
        size += strlen(p->name);
        count++;
        p = p->nxt;
    }

    size = size + 1; // for the '\0'

    char *arr[count][size];
    p = list->head;
    count = 0;

    while (p != NULL) {
        strcpy(arr[count], p->name);
        count++;
        p = p->next;
   }
   return arr;
}

I then go to try and print it out in my main function on a certain node. and I get a segmentation fault.

char *test = return(node1);
for (i = 0; i < 5; i++) {
     printf("%s", test[i]);
}

Upvotes: 0

Views: 488

Answers (1)

Amadan
Amadan

Reputation: 198324

Your arr is local to the (unfortunately named) function. When the function exits, the space is deallocated. If you use that pointer afterwards, you are indexing into unknown, and most likely somewhere you're not supposed to (which results in a segfault).

When you want to allocate space in a function and return a pointer, you should use malloc (or equivalent), and remember to free the space afterwards. An alternate way is to have the pointer be a parameter to the function, and leave the reponsibility for allocation (and deallocation) to the caller (like fgets does).

Approach 1 (allocation inside the function):

char *foo() {
  char *arr = malloc(100);
  return arr;
}

/* somewhere else */
char *arr = foo();
/* use arr */
free(arr);

Approach 2 (allocation outside the function):

void foo(char *arr, size_t size) {
  /* do stuff to arr */
}

/* somewhere else */
char *arr = char[100];
foo(arr, 100);

EDIT: Was wrong. Ignore what was here.

Upvotes: 3

Related Questions