0
    char arr[120];
    for (k = 0; k < 120; ++k) {
        arr[k] = (char *)malloc(1);
    }
    for (k = 0; k < 120; ++k) {
        free(arr[k]);
    }

I have the above code. I was wondering why I am getting a Segmentation Fault error when I compile and run the code. Any advice for changes?

I just want to point out that the code above is for a school project.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
CLearner
  • 17
  • 2
  • There is no need to cast the output of malloc in C. see this https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc#:~:text=If%20you%20use%20malloc%20in,will%20return%20a%20void*%20type. – Krishna Kanth Yenumula Oct 25 '20 at 07:09
  • 1
    Your compiler complained about your code. Heed your compiler. It knows a lot more about C than you do. – Jonathan Leffler Oct 25 '20 at 07:27

1 Answers1

1

You are storing char* objects into an array that can only store char objects. That's undefined behavior. You need:

char* arr[120];
Nikos C.
  • 50,738
  • 9
  • 71
  • 96
  • I wish modern compilers would default to treating this type of mistake as a fatal error with a meaningful diagnostic message. – chqrlie Oct 25 '20 at 11:04