简体   繁体   中英

C malloc with string array

I am trying to make an array of strings by representing this array by a char** . However, I am getting a segmentation fault on this line:

char** values = malloc(count*sizeof(char*)+1); //+1 for terminating NUL

Any advice? count is a variable of type size_t . Thanks for any and all help!

Edit: Code before it:

size_t count = 0;
char** counter = params;
while(*counter) {
    count++;
    counter += sizeof(char*);
}
count++; //one space for NULL
char** values = malloc((count + 1) * sizeof(char*)); // +1 for terminating NULL

Since values is an array of pointers, the code you are using is problematic. It should be:

char** values = malloc((count + 1) * sizeof(char*)); // +1 for terminating NULL

since you need sizeof(char*) bytes (and not 1 byte) for the terminating NULL. However, it is not clear that this line alone is causing the segfault... Maybe it is because of memory alignment issues (that arise because of the misplaced +1 in the line you are using)...

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