Quote:
Originally Posted by psio15
Code:
/*
/ Ptr is allocated 1000 "lines" 50 "spaces" wide, all the size of char
*/
char *ptr = (char *)malloc(1000*50*sizeof(char));
char buffer[100];
int dict[1000];
int i = 0;
|
So
ptr is your data array,
buffer is a temporary buffer you use to read the lines into,
dict is a hash array of sorts (with
convertString() being the hash function), and
i being the line number (starting from zero). I'll omit the
dict and
convertString() bits below to make the issue clearer.
The next bit is the problem:
Quote:
Originally Posted by psio15
Code:
while(fgets(buffer, sizeof buffer, fp) != NULL)
{
*ptr++ = buffer;
i++;
}
|
You do read the line (assuming it is less than 99 characters including the newline, otherwise it'll take more than one call to read the entire line -- so it'd be a good idea to set a bit bigger size to
buffer, just in case). However, you don't check if you read too many lines, and you just copy the first char of
buffer to the
ptr,
and increase ptr[I], making it very difficult to retrieve the actual start of
ptr. Later on, you try to free a pointer
within the allocated array, which is obviously an error. Do not modify
ptr itself, use some kind of an offset (
50*i perhaps).
I believe you should use
strspn() and
strcspn() to skip the leading and trailing newlines and control characters (and whitespace), and then
memcpy() to copy the interesting bit (not exceeding the allocated space) to the
ptr array -- or write your own "copy trimmed string" function. The details depend on whether you want the
ptr array to be a two-dimensional character array (without end-of-string zero bytes), or an array of strings (each with an end-of-string zero byte).
If you want to use a dynamic array of strings, consider the following:
Code:
#include <stdlib.h>
#include <string.h>
int lines_max = 0;
int lines = 0;
char **line = NULL;
/* line[i] exists, if (i >= 0 && i < lines). */
/** addline() - Add a new line to the line array
* @string Pointer to the string
* @length Length to copy
* Return value will be the line number, or negative if out of memory.
*/
int add_line(char const *const string, size_t const length)
{
/* Make sure line array has room for another line. */
if (lines >= lines_max) {
size_t const max = (size_t)lines + (size_t)512;
char **tmp;
tmp = realloc(line_ptr, sizeof(char *), max);
if (!tmp)
return -1;
line = tmp;
lines = (int)max;
}
/* Allocate line buffer */
line[lines] = malloc(length + (size_t)1);
if (!line[lines])
return -1;
/* Copy string */
memcpy(line[lines], string, length);
line[lines][length] = 0;
/* Increase lines, but return the prior value. */
return lines++;
}