Very confused on why I'm getting a "Segmentation Fault (core dumped)".
const int bufSize = 32;
char* splitStrings[bufSize];
splitStrings[0][0] = 'a';
splitStrings[0][1] = '\0';
printf("testchar: %c",splitStrings[0][0]);
printf("teststr: %s",splitStrings[0]);
Thanks for any help
I think you want to define a 2-D array with char elements.
To do this make these steps:
First
Define a char**
array of pointers.
char **splitStrings[bufSize];
Second
Allocate memory for row:
splitStrings = malloc(bufSize*sizeof(char*));
Third
For each row allocate memory for its columns.
for (int i=0;i<bufSize;i++){
splitStrings[i]=malloc(bufSize*sizeof(char*));
}
Code
#include <stdio.h>///for printf()
#include <stdlib.h>///for malloc()
int main(void){
const int bufSize = 32;
char **splitStrings;
splitStrings = malloc(bufSize*sizeof(char*));
for (int i=0;i<bufSize;i++){
splitStrings[i]=malloc(bufSize*sizeof(char*));
}
splitStrings[0][0] = 'a';
splitStrings[0][1] = '\0';
printf("testchar: %c\n", splitStrings[0][0]);
printf("teststr: %s\n", splitStrings[0]);
free(splitStrings);
return 0;
}
Further Notes
For more information about 2-D dynamic array see
Using malloc()
function in C to obtain heap memory, never cast the result see
After allocating dynamic memory in Heap never forget to release it by using free()
.
I suggest you read more about how to allocate dynamic memory in C with malloc()
function.
Also check result of malloc()
to ensure true return value(a pointer to allocated memory).
malloc manpage error section
ERRORS calloc(), malloc(), realloc(), and reallocarray() can fail with the following error:
ENOMEM Out of memory. Possibly, the application hit the RLIMIT_AS or RLIMIT_DATA limit described in getrlimit(2).
Last Edition on code
Change malloc(bufSize*sizeof(char));
to malloc(bufSize*sizeof(char*));
this is true way of allocating memory
Because in first case calling free()
on splitStrings
pointer cause memory error. Why?