Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have trouble to copy the string from buffer to a new array which contains strings (char *)

I am trying to use `strcpy’ to copy the strings in buffer to a new array that contains strings (char *). I always received error message of seg fault. But I don’t know why that happen.

char buffer[1024];
FILE *fp1;
fp1 = fopen("input.txt", "r");
char* array[file_row];
int index = 0;

while (fgets(buffer, sizeof(buffer), fp1) != NULL) {
    strcpy(array[index++], buffer);
    printf("%s", buffer);
}

fclose(fp1);
return 0;

This is my part of codes, I hope that can provide enough information about my problem. I can’t allocate memory for that array since its size is fixed, and I think I don’t need to allocate each slot in array since strcpy did that for me. Also, I can print the content in buffer, so I think buffer worked well. Then I am not sure why this error happened. Can someone help me please?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

THis

char* array[file_row];

is an array of pointers that point nowhere. In order to strcpy to them they have to point to a section of memory large enough to take the string. The easy solution is to use strdup it will allocate the memory and copy the string for you

instead of

  strcpy(array[index++], buffer);

do

  array[index++] = strdup(buffer);

(on windows you need _strdup)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading