简体   繁体   中英

Advice on using pointers for malloc and free

    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.

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

char* arr[120];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM