c - Segmentation fault after resizing array -
i'm trying implement algorithm, sorts words length of 100 chars alphabetically. idea each word fgets(), check if length under 100 chars , if so, put array of strings after resizing it.
now i'm getting segfault in line 37, supposed use strcpy() put string string array.
i'm pretty sure resizing of array responsible error, since segfault occurs @ 2nd word (or 2nd iteration of while-loop)
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> int cmpstr(const void* a, const void* b){ const char* aa = *(const char**)a; const char* bb = *(const char**)b; return strcmp(aa,bb); } int main(int argc, char* argv[]){ //buffer array check word length char barray[102]; char* buffer = barray; //main array pointer char** list; list = (char**)calloc(1, sizeof(char*)); //if calloc fails if(list == null){ perror("calloc() fails @ main array"); return -1; } //memory allocation first string list[0] = (char*) calloc(102, sizeof(char)); if(list[0] == null){ perror("calloc() fails @ first array element"); return -1; } //string array index int counter = 0; //print flag int flag = 0; //create unsorted list while(fgets(buffer, 103, stdin) != null){ //breakpoint 1 if(buffer[0] == '\n'){ break; } for(int = 0; < 101;i++){ //if word of legit length , not last 1 if(buffer[i] == '\n'){ buffer[i] = '\0'; strcpy(list[counter], buffer); //segfault @ 2nd iteration counter++; list = realloc(list, (counter + 1) * sizeof(char*)); list[counter] = (char*)calloc(102,sizeof(char)); flag = 1; break; } } if(flag==1){ flag = 0; break; } //if word long if(buffer[100] != '\0'){ printf("word long!"); } else{ strcpy(list[counter], buffer); counter++; } } //sort list qsort(list, counter, sizeof(char*), cmpstr); //print list for(int = 0; < counter; i++){ printf("%s\n", list[i]); } //free memory for(int = 0; < counter; i++){ free(list[counter]); } }
(also, feel free criticise code if see other mistakes made :) )
well yeah, looks set list = (char**)calloc(1, sizeof(char*));
means have space 1 char*
in list
. when try strcpy
list[1]
segfault.
Comments
Post a Comment