Skip to content
Advertisement

debugging c using heap memory [closed]

I am working with heap memory and I wrote an example below:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){
  FILE *fd;

  //Alocate memory on the heap;
  char *UserInput = malloc(20);
  char *OutputFile = malloc(20);

  if(argc < 2){
    printf("Usage: %s <string to be written to /tmp/notes>n", argv[0]);
    exit(0);
  }

  //Copy data into the heap memory
  strcpy(OutputFile, "/tmp/notes");
  strcpy(UserInput, argv[1]);

  //Print out some debug messages
  printf("___DEBUG___n");
  printf("[*] UserInput @ %p: %sn", UserInput, UserInput);
  printf("[*] OutputFile @ %p: %sn", OutputFile, OutputFile);
  printf("[*] Distance between: %ldn", UserInput - OutputFile);
  printf("_________________nn");

  //Writing the data out to the file
  printf("Writing to "%s" to the end of %s...n", UserInput, OutputFile);
  fd = fopen(OutputFile, "a");
  if (fd == NULL){
    fprintf(stderr, "Error openning %sn", OutputFile);
    exit(1);
  }

  fprintf(fd, "%sn", UserInput);
  fclose(fd);

  return 0;
}

I execute is as : ./heap test and the output is:

___DEBUG___
[*] UserInput @ 0x1a13010: test
[*] OutputFile @ 0x1a13030: /tmp/notes
[*] Distance between: -32
_________________

I think something wrong is happening with “Distance between” \ max length of argv[1] in int type is “31” of integers\ and max length of argv[1] in char type is “58” of characters\ for example:

 ./heap 123...01 => 31 integers
 ./heap qqq..qqq => 58 characters

after that I face an open error… why -32 is happening for distance between?

Advertisement

Answer

There is nothing wrong here. The pointers are assigned by the malloc() function, which can and does assign fairly arbitrary values to the pointers. A normal malloc() implementation will reserve a few bytes to mark the length of the allocated buffer, as well as taking advantage of existing buffer sizes on the free list. So if you allocate two buffers, as you have done, there is nothing saying they have to be contiguous in heap space. In fact, they will not be.

I don’t know what you are trying to do here, but the ‘distance between’ two malloc() pointers isn’t going to be the exact length of the buffers, ever.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement