Answer the question
In order to leave comments, you need to log in
Why is part of an array overwritten in C?
I get a list of disks and specifically add two strings "ABC" and "DEF" to the allDisks array.
After passing through the array with the get_files function, the list of disks disappears, but "ABC" and "DEF" remain.
Tell me why this happens, where the first lines are lost and how to fix it?
#include <windows.h>
#include <stdio.h>
#include <string.h>
#define MAX_COUNT_DISKS 26
void get_disks(char * allDisks[])
{
char buf[128];
int i = 0;
GetLogicalDriveStringsA(sizeof(buf), buf);
for (char *s = buf; *s; s += strlen(s) + 1)
{
if (GetDriveTypeA(s) == 2 || GetDriveTypeA(s) == 3)
{
allDisks[i] = s;
++i;
allDisks[7] = "ABC";
allDisks[8] = "DEF";
}
}
}
void get_files(char * allDisks[])
{
}
int main()
{
char * allDisks[MAX_COUNT_DISKS] = { 0 };
get_disks(allDisks);
get_files(allDisks);
return 0;
}
Answer the question
In order to leave comments, you need to log in
void get_disks(char * allDisks[]) { char buf[128]; ... for (char *s = buf; *s; s += strlen(s) + 1) { ... allDisks[i] = s; ... allDisks[7] = "ABC"; allDisks[8] = "DEF"; } }
After passing through the array with the get_files function, the list of disks disappears, but "ABC" and "DEF" remain.
Tell me why this happens, where the first lines are lost and how to fix it?
This is because you're putting inallDisks
pointers to a stack arraybuf
, which gets destroyed when the function exitsget_disks
. And the lines "ABC" and "DEF" are constant lines, they exist all the time the program is executed.
You can fix it, for example, by allocating memory for the lines that are written toallDisks
:void get_disks(char * allDisks[]) { char buf[128]; int i = 0; GetLogicalDriveStringsA(sizeof(buf), buf); for (char *s = buf; *s; s += strlen(s) + 1) { if (GetDriveTypeA(s) == 2 || GetDriveTypeA(s) == 3) { allDisks[i] = strdup(s); ++i; allDisks[7] = "ABC"; allDisks[8] = "DEF"; } } }
allDisks[i] = s;
here you assign to a variable a pointer to a piece of memory located in the variable
, and this variable is local automatic in the function, and after exiting this piece of memory is reused by the program.
How to fix:
create a copy of the string here. Or use a static buffer. I won’t tell you more precisely, I haven’t worked with C for a long time.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question