c - Using Strings and Malloc/Realloc -


i'll honest, i'm complete novice @ c. thus, things malloc , realloc alien concepts. think have basics down, can't quite there 100%.

while (int args = scanf("%s", string)) {     if (args < 0) break;     count++;      if (array == null) {         array = (char *) malloc(strlen(string));          if (array == null) {             printf("error allocating memory");             exit(1);         }     } else {         printf("%s %d\n", string, strlen(string));         array = (char *) realloc(array, (sizeof(array) + strlen(string) + 1));          if (array == null) {             printf("error allocating memory");             free(array);             exit(1);         }          printf("%lu\n", sizeof(array));     }      strcpy(&array[count - 1], string); } 

it's reading terminal - cat file | ./program , bunch of words of arbitrary length. i'm trying them array (array).

edit: should mentino i'm apparently trying access memory didn't allocated: malloc: *** error object 0x7fe9e04039a0: incorrect checksum freed object - object modified after being freed. *** set breakpoint in malloc_error_break debug segmentation fault: 11

looks don't understand pointers, strings , char*s in c. example, here description.

here main problems:

  1. char* not string type. it's pointer place in memory, string data lies char-by-char , terminates char '\0' (null terminator)
  2. thus, strcpy copies bunch of chars 1 place (string variable) another. in case, copies them array, starting element count-1. so, if read string longer 1 char, lost data. want sum lengths of preceding strings , write starting place.
  3. the remaining problem consequence: don't allocate space null terminator during first iteration (which causes strcpy access non-allocated memory , leads message see after program's termination).

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -