Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault on program with scanf

Tags:

c

This is a small piece of code that I made while trying to understand how malloc and pointers work.

#include <stdio.h>
#include <stdlib.h>

int *buffer (int count)
{
  int *buffer = malloc (count * sizeof(int));

  for (int i = 0; 0 <= i && i < count; i++)
    {
      buffer[i] = 0;
    }

  return &buffer;
}

int main ()
{
  int size = 0;
  int i = 0;
  scanf ("%d", &size);

  int *num = buffer (size);
  while (i < size)
    {
      scanf ("%d", &num[i]);
      i++;
    }
}

For some reason that I can't understand, I keep getting a segmentation fault. This error repeatedly happens on the last scanf() and I do not know why. I know i have to pass pointer to scan f and num is already a pointer so i thought that i would not need to include the &. But, I received a segmentation fault earlier if i do not. Also, I believe I have allocated the correct amount of space using malloc but I am not sure. Any help with what is happening here would be appreciated.

like image 869
Michael Hemmelgarn Avatar asked Apr 27 '26 06:04

Michael Hemmelgarn


1 Answers

You returned the pointer to the local variable buffer, which will banish on exiting the function buffer.

You should remove the & used in the return statement and return the pointer to allocated buffer.

Also checking whether malloc() is successful should be added.

like image 170
MikeCAT Avatar answered Apr 29 '26 18:04

MikeCAT