Ern*_*nio 2 c string pointers realloc
考虑代码:
char *word = NULL; // Pointer at buffered string.
int size = 0; // Size of buffered string.
int index = 0; // Write index.
char c; // Next character read from file.
FILE *file = fopen(fileDir, "r");
if (file)
{
while ((c = getc(file)) != EOF)
{
printf("Current index: %d, size: %d, Word: %s\n", index, size, word);
if (isValidChar(c))
{
appendChar(c, &word, &size, &index);
}
else if (word) // Any non-valid char is end of word. If (pointer) word is not null, we can process word.
{
// Processing parsed word.
size = 0; // Reset buffer size.
index = 0; // Reset buffer index.
free(word); // Free memory.
word = NULL; // Nullify word.
// Next word will be read
}
}
}
fclose(file);
/* Appends c to string, resizes string, inceremnts index. */
void appendChar(char c, char **string, int *size, int *index)
{
printf("CALL\n");
if (*size <= *index) // Resize buffer.
{
*size += 1; // Words are mostly 1-3 chars, that's why I use +1.
char *newString = realloc(*string, *size); // Reallocate memory.
printf("REALLOC\n");
if (!newString) // Out of memory?
{
printf("[ERROR] Failed to append character to buffered string.");
return;
}
*string = newString;
printf("ASSIGN\n");
}
*string[*index] = c;
printf("SET\n");
(*index)++;
printf("RET\n");
}
Run Code Online (Sandbox Code Playgroud)
输入:
血腥
输出:
Current index: 0, size: 0, Word: <null>
CALL
REALLOC
ASSIGN
SET
RET
Current index: 1, size: 1, Word: B** // Where * means "some random char" since I am NOT saving additional '\0'. I don't need to, I have my size/index.
CALL
REALLOC
ASSIGN
CRASH!!!
Run Code Online (Sandbox Code Playgroud)
所以基本上 - *string [*index] ='B'有效,当index是第一个字母时,它会在第二个字母崩溃.为什么?我可能搞乱了分配或指针,我真的不知道(新手):C
谢谢!
编辑 我也想问 - 我的代码还有什么问题吗?
这个表达式不正确:
*string[*index] = c;
Run Code Online (Sandbox Code Playgroud)
由于[]优先级高于*s,代码会尝试将双指针解释为指针string数组.当*index为零时,您获得正确的地址,因此第一次迭代通过纯巧合工作.
您可以通过使用括号强制执行正确的操作顺序来解决此问题:
(*string)[*index] = c;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |