-2

I am new to C programming and was attempting to write a code in which values of variables x and y are taken from the user in the main function of File1.c. All other functions in the file use the value of these variables. I have used 'extern' keyword to declare it in Header file Header.h and this header file also makes use of the values of x and y entered by the user. Another File2.c also makes use of these variables. Both File1.c and File2.c include Header.h

I have defined variables x and y as global variables in File1.c but I am constantly getting segmentation faults. How should I proceed?

EDIT: Here is the code:

#include<stdio.h>
#include<Header.h>
 int x,y;
 int main() 
{
  uint16_t *Buffer_1 = (uint16_t *)malloc(sizeof(uint16_t) *x*y*256);
  uint16_t *slice = (uint16_t *)malloc(sizeof(uint16_t)*x*y);
  printf("Enter value of x: );
  scanf("%d",&x);
  printf("Enter value of y: );
  scanf("%d",&y);
  memcpy(slice,Buffer_1,x*y*sizeof(uint16_t));
 }

I get segmentation fault at memcpy. I have declared variables x,y in Header.h as follows:

#include <stdio.h>
extern int x;
extern int y;
rdx1994
  • 7
  • 2
  • 2
    Please post your code. Also, post the callstack or the location where the segfault is happening. Else, it is very difficult to imagine the code based on your description and give a solution. Also, you can be fairly sure, the extern keyword is not causing your seg faults. : ) – Jay Dec 07 '16 at 11:28
  • 1
    And while you post the offending code as Jay recommends, please try to make it ["short, self-contained, and compile-able"](http://sscce.org/) so that those trying to answer can quickly get to the root cause. – ArjunShankar Dec 07 '16 at 11:30
  • Consider allocating memory *after* you know the value of x and y. And never ignore the return value of scanf(). – Hans Passant Dec 07 '16 at 12:15
  • Thank you. This solved the problem. I didn't realise this could be a problem and thought extern would be the problem. – rdx1994 Dec 07 '16 at 12:26
  • 1
    `EXTERN` is **not** a keyword, but `extern` is. – too honest for this site Dec 07 '16 at 13:34

1 Answers1

1

Problem is that you have x and y equal to 0 when you are allocating the memory and later you are making these memory for copy, this will lead to crash.

You need to allocate after

scanf("%d",&y);

Also check for NULL before proceeding.

MGpro
  • 33
  • 4