Hi All,
I am using the array of pointers and storing the address of string.This is a global list.
So i am using extern to give the reference of this list to another file and using reading the data from this string.
But list is being corrupted and string is missing some characters in string. eg.
In file A:
char *str[512];
char line[512];
while(fgets(line, 512, fp) != NULL) str[count++] = line;
in file B:
char* alert;
for(i = 0 ; i < count; count++) alert = str;
Anyone can suggest me why it is being corrupted.that would be appreciated. It's crashing also in gcc for linux and but not solaris.
Thanks!
You are storing the string in the same buffer every time you fgets, overwriting anything previously read, and every pointer in your array just points to this same buffer. Without seeing the code it's only a guess, but is that buffer a local variable? It doesn't even exist except when the function it's in is being called, and at other times may be used for other memory, hence the further corruption. You need to store the data globally, not the pointer, so, a global array of strings:
#include <stdio.h>
extern char str_table[512][512];
int main(void)
{
int line=0;
while(fgets(str_table[line], 512, stdin) != NULL)
{
line++;
if(line >= 512)
{
fprintf(stderr, "Too many lines\n");
return(1);
}
}
}
Or if you wanted to just store pointers, you could use strdup:
#include <string.h>
#include <stdio.h>
extern char *str_table[512];
int main(void)
{
int line=0;
char buf[512];
while(fgets(buf, 512, stdin) != NULL)
{
str_table[line]=strdup(buf); // Create a persistent copy of the string in heap memory
line++;
if(line >= 512)
{
fprintf(stderr, "Too many lines\n");
return(1);
}
}
line--;
while(line >= 0)
{
free(str_table[line]); // Get rid of the persistent copies of strings
line--;
}
}
Thank you!
I will use it.