'Weird segfault on variable assignment [closed]
I have a weird segfault with the following program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void bugtest(char **output)
{
*output = malloc(10);
if (! *output)
{
fprintf(stderr, "malloc() failed\n");
return;
}
memset(*output, 0, 10);
for (char i = 0; i < 6; i += 2)
{
*output[i / 2] = i;
}
}
int main (int argc, char *argv[])
{
char *output = NULL;
bugtest(&output);
printf("%s\n", output);
return 0;
}
*output is not NULL but it crashes at *output[i / 2] = i;. Does anyone know why?
Solution 1:[1]
*output[i / 2] Operator precedence. Should have been (*output)[i / 2].
Instead of dragging that ugly pointer-to-pointer across your whole function (and causing bugs because you do), then do this:
void bugtest(char **output)
{
char* result = malloc(10);
if (result == NULL)
{
fprintf(stderr, "malloc() failed\n");
return;
}
memset(result, 0, 10);
for (char i = 0; i < 6; i += 2)
{
result[i / 2] = i;
}
*output = result;
}
Unrelated to your bug, it doesn't make any sense to print the symbol values 0 to 6 as a string here: printf("%s\n", output);. Symbol 0, the null terminator, is particularly troublesome since it will just stop the printing. Perhaps you meant to print integer values?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
