Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

c - segmentation fault on trying to allocate memory for a passed argument

I am trying to make a python-like list in C and I tried the below code I identified the line at which the error occurs: *list[i] = (char*) malloc(strlen(buffer) + 1);.

But I have no idea how to fix it I am using gcc as a compiler and I am accounting for the null byte I also checked that realloc makes the needed memory to store the pointer that malloc will return but still the problem is still there for some reason.

One thing to note is that it actually works only if I called the function once which makes me doubt that my syntax in *list[i] isn't compiled the way I think it is which is to be equivalent to fileNames[i]

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

void dynamicListHandler(char ***list, char* buffer) {
    static int listSize = sizeof(char*);
    static int i = 0;

    *list[i] = (char*) malloc(strlen(buffer) + 1);
    strcpy(*list[i], buffer);   

    listSize += sizeof(char*);
    *list =  (char**) realloc(*list, listSize); 
    if(*list == NULL){ 
        printf("couldn't allocate the requested memory
");
        exit(-1);
    }

    i++;
}

int main() {
    char **fileNames;
    fileNames = (char**) malloc(sizeof(char*));

    dynamicListHandler(&fileNames, "Hello World1");
    dynamicListHandler(&fileNames, "Hello World2");
}
question from:https://stackoverflow.com/questions/65952137/segmentation-fault-on-trying-to-allocate-memory-for-a-passed-argument

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...