| |||||||||||||||||||||||||||||
|
Hello all, The goal of my program is to create a dynamic array of a struct type. The struct type has two strings inside it. From time to time I want to copy strings into the strings in the dynamic array. Then increase the size of the dynamic array. I have narrowed the problem down to the realloc function but I still don't know why it says segmentation fault or hangs (sometimes). Here is the simplified code which exhibits the problem: /*libraries here */ #define SIZEOF_BUCKETSTRUCT 70 #define SIZEOF_HOSTNAME 20 #define SIZEOF_DESCRIPTION 50 int bucketsize = 1; struct bucket { char *hostname; char *description; }; void function1(struct bucket *valid) { valid[bucketsize - 1].hostname = malloc (sizeof(char) * 20); strncpy(valid[bucketsize - 1].hostname, "test hostname", 20); valid[bucketsize - 1].hostname[19] = '\0'; printf("hostname is %s \n", valid[bucketsize - 1].hostname); valid[bucketsize - 1].description = malloc (sizeof(char) * 50); strncpy(valid[bucketsize - 1].description, "test buf", 50); valid[bucketsize - 1].description[49] = '\0'; printf("description is %s \n", valid[bucketsize - 1].description); /* problem is here */ valid = (struct bucket *) realloc (valid, 70 * ((bucketsize) + 1)); bucketsize++; } int main() { struct bucket *valid; valid = (struct bucket *) malloc (SIZEOF_BUCKETSTRUCT); if (valid == NULL) { printf("error in allocating memory \n"); exit(1); } function1(valid); function1(valid); return 0; } Thank you, Jonathan Shan
| ||||||||||||||||||||||||||||
© 2004-2008 readlist.com