P
P
polger2019-01-22 01:52:42
C++ / C#
polger, 2019-01-22 01:52:42

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;
}

5c464df12df17688188162.jpeg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2019-01-22
@polger


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 in allDiskspointers to a stack array buf, which gets destroyed when the function exits get_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 to allDisks:
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";
    }
  }
}

A
Alexeytur, 2019-01-22
@Alexeytur

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 question

Ask a Question

731 491 924 answers to any question