TransWikia.com

Segmentation error while returning a pointer from an array using malloc() in C

Stack Overflow Asked by Abner on January 17, 2021

maybe it’s a dumb question but I’m new in C. I’m trying to return a pointer from a function using malloc. I made an array with strtok. Here it’s the code of the function from which I’m trying to return the pointer:

int *data(){
    
  int longi=0, *array=(int *) malloc(4 * sizeof(int));
  char buffer[1024];     
  char *aux;       
  printf("Enter if approved(A) or failed (F) separated by a comma ",": n");
  fgets(buffer,1023,stdin); 
  aux=strtok(buffer, ","); 
  while(aux)                 
  {
      array[longi]=aux; 
      longi++;                 
      aux=strtok(NULL, ","); 
  } 

  printf("%s", array[0]);
  return array;
}

And here is my main function:

int main(){
  int *arr=data();
  printf("%s",arr[0]); /*segmentation error */
  return 0;
}

2 Answers

The segmentation fault occurs because you are trying to print part of your array as a string (%s). When using %d or %c (with char casting) it does not give that error. However, it still doesn't make sense, since you are trying to put a pointer to the beginning of a string inside an array of integers. I'd suggest allocating an array of characters instead of integers, and making sure you've got a single character inside aux, then adding it to the array. You also need to make sure you don't accept more than 4 different characters, otherwise you might still have a buffer overflow.

Correct answer by Liel Fridman on January 17, 2021

printf when flag is %s is trying to read string from allocated memory, you giving an integer so this why it gives a segfault replace array[longi]=aux; with array[longi]=atoi(aux); atoi will convert from string to integer, and for both printfs replace %s with %d

Answered by bari barix on January 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP